当系统运行在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());
}
}