Spring注解驱动 @Conditional按照条件注册Bean

1. @Conditional使用流程

编写条件类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/** 实现Condition接口 */
public class MyCondition implements Condition {
/**
* 条件方法,满足则创建Bean
* ConditionContext: 判断条件能使用的上下文(环境)
* AnnotatedTypeMetadata: 注解信息
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 能获取ioc的Bean工厂
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
// 能获取类加载器
ClassLoader classLoader = context.getClassLoader();
// 能获取环境信息
Environment environment = context.getEnvironment();
// 能获取Bean定义的注册类
BeanDefinitionRegistry registry = context.getRegistry();

// 判断当前系统是不是Windows,是则满足条件
String property = environment.getProperty("os.name");
return property.contains("Windows");
}
}

配置类

1
2
3
4
5
6
7
8
@Configuration
public class BeanConfig {
@Bean
@Conditional({MyCondition.class}) // 满足条件才注册
public Person person() {
return new Person("jack", 10);
}
}

测试方法

1
2
3
4
5
6
@Test
public void test() {
ApplicationContext ioc = new AnnotationConfigApplicationContext(BeanConfig.class);
String[] names = ioc.getBeanDefinitionNames();
Arrays.stream(names).forEach(System.out::println);
}
panchaoxin wechat
关注我的公众号
支持一下