【Spring源码解析】组件注册-@Condition条件注册bean

前言

接上一篇 Spring源码解析之@Lazy懒加载Bean

未添加条件前

  1. 配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Configuration
public class BeanConfig2 {

@Lazy
@Bean
public Person person() {
System.out.println("容器中注册Person...");
return new Person("config", 18);
}

@Bean("linux")
public Person person1() {
return new Person("linux", 20);
}

@Bean("windows")
public Person person2() {
return new Person("windows", 21);
}
}
  1. 测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* person
* linux
* windows
* 容器中注册Person...
* {person=Person{name='config', age=18}, linux=Person{name='linux', age=20}, windows=Person{name='windows', age=21}}
*/
@Test
public void test03() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig2.class);
String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
for (String name: beanNamesForType) {
System.out.println(name);
}
Map<String, Person> beansOfType = applicationContext.getBeansOfType(Person.class);
System.out.println(beansOfType);
}

条件注入

  1. 条件配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Configuration
public class BeanConfig2 {

@Lazy
@Bean
public Person person() {
System.out.println("容器中注册Person...");
return new Person("config", 18);
}

@Conditional({MacCondition.class})
@Bean("mac")
public Person person0() {
return new Person("mac", 19);
}

@Conditional({LinuxCondition.class})
@Bean("linux")
public Person person1() {
return new Person("linux", 20);
}

@Conditional({WindowsCondition.class})
@Bean("windows")
public Person person2() {
return new Person("windows", 21);
}
}
  1. 条件实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @author cuishiying
* @date 2021-01-22
*/
public class MacCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
Environment environment = context.getEnvironment();
BeanDefinitionRegistry registry = context.getRegistry();
String[] beanDefinitionNames = registry.getBeanDefinitionNames();

String property = environment.getProperty("os.name");
if (property.contains("Mac")) {
return true;
}
return false;
}
}

其他条件类似~

  1. 测试
1
2
3
4
5
6
7
8
9
10
11
12
/**
* person
* mac
*/
@Test
public void test04() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig2.class);
String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
for (String name: beanNamesForType) {
System.out.println(name);
}
}

最后

本篇到此结束,欢迎大家关注公众号【当我遇上你】。