@Conditional({}):按照一定的条件进行判断,满足条件给容器中注册bean。 如果将其注解在类上,则是满足当前条件下,这个类中配置的所有bean注册才能生效。 自定义判断条件,需要实现org.springframework.context.annotation的Condition接口,并重写matches()方法。
举个例子:如果系统是Windows,给容器中注册("windows")
如果系统是Linux,给容器中注册("linus")
创建一个LinuxCondition类并实现Condition接口
public class LinuxCondition implements Condition{
/* ConditionContext:判断条件能使用的上下文环境
* AnnotatedTypeMetadata:注解的注释信息
*
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 判断是否是Linux系统
//1、获取当前运行环境,这里面封装了jvm信息,环境变量等
Environment environment = context.getEnvironment();
//2、获取到bean定义的注册类
BeanDefinitionRegistry registry = context.getRegistry();
String property = environment.getProperty("os.name");
if(property.contains("linux")) {
return true;
}
return false;
}
}
创建一个WindowsCondition类并实现Condition接口
public class WindowsCondition implements Condition{
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 判断是否是Windows系统
Environment environment = context.getEnvironment();
String property = environment.getProperty("os.name");
if(property.contains("Windows 10")) {
return true;
}
return false;
}
}
然后在配置类里进行配置,部分代码如下:
@Conditional({WindowsCondition.class})
@Bean("windows")
public Person person01() {
return new Person("windows",13);
}
@Conditional({LinuxCondition.class})
@Bean("linus")
public Person person02() {
return new Person("linus",58);
}