条件注解
条件注解就是在满足一定条件下,配置才会生效。我们以Linux和Windows操作系统为例,在Linux系统下查看目录命令为ls,在Windos系统下目录命令为dir,来实现根据当前操作系统实现不同的功能。
1、显示目录命令接口
先定义一个显示目录命令的接口。
public interface ShowCmd {
String showCmd();
}
2、实现接口
分别实现Linux下和Windows下的实例
public class LinuxShowCmd implements ShowCmd{
public String showCmd() {
return "ls";
}
}
public class WindowsShowCmd implements ShowCmd {
public String showCmd() {
return "dir";
}
}
实现接口Condition
实现Linux和Windows下的条件
public class LinuxCondition implements Condition {
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
String osName = conditionContext.getEnvironment().getProperty("os.name");
return osName.toLowerCase().contains("linux");
}
}
public class WindowsCondition implements Condition {
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
String osName = conditionContext.getEnvironment().getProperty("os.name");
return osName.toLowerCase().contains("windows");
}
}
配置Bean
@Configuration
public class JavaConfig {
@Bean("cmd")
@Conditional(WindowsCondition.class)
ShowCmd winCmd() {
return new WindowsShowCmd();
}
@Bean("cmd")
@Conditional(LinuxCondition.class)
ShowCmd linuxCmd() {
return new LinuxShowCmd();
}
}
测试
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);
ShowCmd cmd = (ShowCmd) ctx.getBean("cmd");
String s = cmd.showCmd();
System.out.println("s = " + s);
}
}
结果显示
多环境切换
在公司开发中,我们需要在开发、生产环境下进行快速切换,这时可以是用Spring中的Profile来解决这个问题,如下:
可以看出Profile注解底层也是Condition实现的,接下来定义一个数据源类DataSource
public class DataSource {
private String url;
private String username;
private String password;
//省略get/set方法
配置Bean
@Configuration
public class DataConfig {
@Bean("ds")
@Profile("dev")
DataSource devDataSource() {
return new DataSource("jdbc:mysql:///school","user","123");
}
@Bean("ds")
@Profile("prod")
DataSource proDataSource() {
return new DataSource("jdbc:mysql://192.168.12.34:3306/school", "user", "321");
}
}
加载配置类,测试结果
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("prod"); //设置环境
ctx.register(DataConfig.class); //加载配置类
ctx.refresh(); //刷新
DataSource ds = (DataSource) ctx.getBean("ds");
System.out.println(ds.toString());
}
}
会发现,当设置prod环境时,数据源为prod环境下的参数。证明实现了多环节切换。