按照条件注册bean
使用@Conditional
注解来控制bean的注册
使用步骤
- 先实现Condition接口,条件写在matches方法里
注意事项:Condition接口
是org.springframework.context.annotation.Condition,别选错了
public class MyCondition implements Condition {
/**
* @param context 判断条件能使用的上下文(环境)
* @param metadata 当前标注了condition注解的类的注释
* @return 是否需要注册bean
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 1.能获取到ioc锁使用的bean工厂
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
// 2.能获取到ioc锁使用的类加载器
ClassLoader classLoader = context.getClassLoader();
// 3.能获取到当前环境信息
Environment environment = context.getEnvironment();
// 4.能获取到bean注册信息
// BeanDefinitionRegistry接口中能注册bean,移除bean
BeanDefinitionRegistry registry = context.getRegistry();
// System.out.println(environment.getProperty("os.name"));
//控制条件
//如果是windows系统则注册bean
if (environment.getProperty("os.name").toLowerCase().contains("windows")) return true;
return false;
}
}
public class LinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
//当前环境为linux系统时注册bean
if (environment.getProperty("os.name").toLowerCase().contains("linux")) return true;
return false;
}
}
- 在需要通过条件控制注册的bean上加上
@Conditional
注解,value为Condition接口的实现类
@Bean
@Lazy
public Person person(){
return new Person();
}
@Bean
@Conditional(value = {MyCondition.class}) //通过条件来决定是否需要注册bean,使用前需要先实现Condition接口
public Person p1(){
return new Person("Windows",12);
}
@Conditional(value = {LinuxCondition.class})
@Bean
public Person p2(){
return new Person("linux",3);
}
- 写测试类
@Test
public void t2(){
try(ConfigurableApplicationContext ioc = new AnnotationConfigApplicationContext(MainConfig.class)){
//查看容器中的person对象名称
String[] beans = ioc.getBeanNamesForType(Person.class);
String s = Arrays.toString(beans);
System.out.println(s);
//查看容器中对象的person对象
Map<String, Person> beansOfType = ioc.getBeansOfType(Person.class);
System.out.println(beansOfType);
}
- 打印结果
[person, p1, p2]
[person, p1]
创建bean
//可以看到linux环境条件限制的类没有被注册
{person=Person{name='null', age=0}, p1=Person{name='Windows', age=12}}