spring中条件注解的使用 @Conditional

一、使用场景

初始化程序的时候,需要判断环境,是Linux还是Windows

二、代码演示

父接口:

public interface ShowCmd {
    /**
     *  展示系统
     * @return
     */
    String showCmd();
}

Linux实现类:

public class LinuxShowCmd implements ShowCmd {
    @Override
    public String showCmd() {
        return "linux";
    }
}

Windows实现类:

public class WindowsShowCmd implements ShowCmd {
    @Override
    public String showCmd() {
        return "windows";
    }
}

设置条件类:

windows条件类:

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
 * @author zb
 * @version 1.0
 * @date 2020/7/18 16:45
 * @description
 */
public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        // conditionContext 获取系统信息, annotatedTypeMetadata 获取注解信息
        String osName = conditionContext.getEnvironment().getProperty("os.name");
        return osName.toLowerCase().contains("win");
    }
}

Linux条件类:

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
 * @author zb
 * @version 1.0
 * @date 2020/7/18 16:45
 * @description
 */
public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        // conditionContext 获取系统信息, annotatedTypeMetadata 获取注解信息
        String osName = conditionContext.getEnvironment().getProperty("os.name");
        return osName.toLowerCase().contains("linux");
    }
}

配置类:

@Configuration
public class JavaConfig {
    /**
     * 这里两个 Bean 的名字一致
     * 判断返回那个 bean 就需要 @Conditional 条件类里面来判断
     * 条件实现类中实现接口Condition,然后方法 matches() 返回 true 的就是需要返回的 bean
     */
    @Bean("cmd")
    @Conditional(WindowsCondition.class)
    public ShowCmd winCmd(){
        return new WindowsShowCmd();
    }
    @Bean("cmd")
    @Conditional(LinuxCondition.class)
    public ShowCmd linuxCmd(){
        return new LinuxShowCmd();
    }
}

测试类:

@SpringBootTest
public class DeskApplicationTests {
    @Resource(name = "cmd")
    private ShowCmd showCmd;
    @Test
    public void contextLoads() {
        System.out.println(showCmd.showCmd());
    }
}

windows平台 测试结果:

控制台打印: windows

你可能感兴趣的:(springboot,spring,springboot,conditional,条件注解,spring条件注解)