使用@Conditional注解,根据条件,判断是否需要创建bean.
代码如下:
@Conditional(WindowsCondition.class)
@Bean
public Person zs(){
Person person = new Person();
person.setAge(21);
person.setName("ls");
return person;
}
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//判断环境变量中是否包含os 包含Windows,就是Windows系统
String property = context.getEnvironment().getProperty("OS");
return property.contains("Windows");
}
}
说明,自定义Condition需要实现Condition接口,只有matches方法返回true,才会生成bean,不满足则不会加载。