1. @Configuration和@Bean注册组件流程
1.1. 依赖
1 | <properties> |
1.2. 编写Bean
1 | // 不需要设置@Component组件注解 |
1.3. 编写Bean配置类
以前写是Bean配置文件,现在改为Bean配置类1
2
3
4
5
6
7 // 标识当前类是一个配置类,配置类==配置文件
public class BeanConfig {
// 给容器注册一个Bean,方法返回类型作为Bean的类型,方法名作为Bean的id
public Person person() {
return new Person("张三", 20);
}
}
1.4. 编写测试方法
以前创建ClassPathXmlApplicationContext,参数是指定配置文件。
现在创建AnnotationConfigApplicationContext,参数是指定配置类1
2
3
4
5
6
7
8
9
public void test() {
// 创建AnnotationConfigApplicationContext,指定配置类class
ApplicationContext ioc = new AnnotationConfigApplicationContext(BeanConfig.class);
Person person = ioc.getBean(Person.class);
String[] names = ioc.getBeanNamesForType(Person.class);
System.out.println(person);
System.out.println(Arrays.toString(names)); // 查看Person在容器中的name
}
2. 给Bean命名
@Bean注解的value或name属性可以给Bean命名1
2
3("person1")
(value = "person1")
(name = "person1")
命名示例1
2
3
4
5
6
7
public class BeanConfig {
("person1") // 给Bean命名
public Person person() {
return new Person("张三", 20);
}
}