spring 条件注解

当系统运行在Windows上时打印dir,在Linux时打印ls

首先定义一个显示文件夹目录的接口:

public interface ShowCmd {
    String showCmd();
}

然后实现Windows下的实例和Linux下的实例:

public class WinShowCmd implements ShowCmd {
    @Override
    public String showCom() {
        return "dir";
    }
}
public class LinuxShowCmd implements ShowCmd {
    @Override
    public String showCom() {
        return "ls";
    }
}

接下来定义Windows和Linux下的条件

public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String osName = (String) conditionContext.getEnvironment().getProperty("os.name");
        boolean win = osName.toLowerCase().contains("win");
        return win;
    }
}
public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String osName = (String) conditionContext.getEnvironment().getProperty("os.name");
        boolean ls = osName.toLowerCase().contains("ls");
        return ls;
    }
}

接下来,在定义Bean的时候,就可以去配置条件注解了:

@Configuration
@ComponentScan(basePackages = "org.javaboy.ioc")
public class JavaConfig {
    @Bean("showCmd")
    @Conditional(WindowsCondition.class)
    ShowCmd winCmd() {
        return new WinShowCmd();
    }

    @Bean("showCmd")
    @Conditional(LinuxCondition.class)
    ShowCmd LinuxCmd(){
        return new LinuxShowCmd();
    }
}

需要给两个Bean取一样的名字,这样在调用时才可以自动匹配。然后给每一个Bean加上条件注解,当条件中matches方法返回true的时候,这个Bean的定义就会生效

public class JavaMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);
        ShowCmd showCmd = (ShowCmd) ctx.getBean("showCmd");
        System.out.println("showCmd.showCom() = " + showCmd.showCom());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值