admin管理员组文章数量:1599733
3.@Condition条件注册
@Condition来指定一定条件下注册组件对像
All Conditions that must match in order for the component to be registered.
所有的条件必须实现Condition接口,重写matches方法,来决定组件是否注册
配置类
@Configuration
public class ConditionConfig {
@Conditional(WindowsCondition.class)
@Bean("bill")
public Person bill(){
return new Person("bill",10);
}
@Conditional(LinuxCondition.class)
@Bean("Linus")
public Person person(){
return new Person("Linus",10);
}
}
WindowsCondition 判断windows环境
public class WindowsCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//获取当前运行环境信息
Environment environment = context.getEnvironment();
//获取当前环境名称
String osName = environment.getProperty("os.name");
return osName.contains("Windows");
}
}
LinuxCondition 判断Linux环境
public class LinuxCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//获取当前运行环境信息
Environment environment = context.getEnvironment();
//获取当前环境名称
String osName = environment.getProperty("os.name");
return osName.contains("Linux");
}
}
测试(系统为Window 7)
@Test
public void person() {
Map<String, Person> beansOfType = annotationConfigApplicationContext.getBeansOfType(Person.class);
System.out.println("beansOfType = " + beansOfType);
}
设置vm的变量来模拟Linux环境,Run Configurations->VM options
添加 Dos.name=Linux
运行结果
版权声明:本文标题:【Spring注解】@Condition条件注册 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1728324853a1154302.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论