条件注解
首先在 Windows 中如何获取操作系统信息?Windows 中查看文件夹目录的命令是 dir,Linux 中查看文件夹目录的命令是 ls,我现在希望当系统运行在 Windows 上时,自动打印出 Windows 上的目录展示命令,Linux 运行时,则自动展示 Linux 上的目录展示命令。
首先定义一个显示文件夹目录的接口:
public interface ShowCmd {    
	String showCmd();
}
然后,分别实现 Windows 下的实例和 Linux 下的实例:
public class WinShowCmd implements ShowCmd {
	@Override
	public String showCmd() { 
		return "dir";	
	}
}
public class LinuxShowCmd implements ShowCmd { 
	@Override
	public String showCmd() {
		return "ls";
	}
}
接下来,定义两个条件,一个是Windows下的条件,另一个是Linux下的条件
public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getEnvironment().getProperty("os.name").toLowerCase().contains("windows");
    }
}
public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getEnvironment().getProperty("os.name").toLowerCase().contains("linux");
    }
}
接下来,在定义 Bean 的时候,就可以去配置条件注解了。
@Configuration
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.showCmd());
    }
}
条件注解有一个非常典型的使用场景,就是多环境切换。

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号