@Configuration & @Bean注册组件到容器
文章目录
最开始的时候我们注册bean到容器中是通过Spring的xml配置文件来注册的, 很麻烦, 这里我们通过@Configuration和@Bean注解配合来注册组件到容器中
@Configuration注解是一个合成注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
...
}
- 可以看到@Configuration注解是@Component注解合成的, 而@Component注解是包扫描(ComponentScan)的对象, 所以说@Configuration注解也是包扫描的对象
1. 创建一个Person实体类(就是我们想要放到容器中的类)
package com.ffyc.spring.model;
public class Person {
int id;
String name;
public Person() {
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
2. 创建一个配置类, 并创建一个注册Person对象到容器中的方法
- 这一步其实就是使用@Configuration注解和@Bean注解
package com.ffyc.spring.config;
import com.ffyc.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PersonConfig {
@Bean
public Person getPerson() {
return new Person();
}
}
3. 创建一个测试类进行测试
package com.ffyc.spring.test;
import com.ffyc.spring.config.PersonConfig;
import com.ffyc.spring.model.Person;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
public static void main(String[] args) {
// ClassPathXmlApplicationContext
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
Person bean = annotationConfigApplicationContext.getBean(Person.class);
System.out.println(bean);
}
}
加载配置类的方式获取Spring容器, 所以是通过AnnotationConfigApplicationContext类
通过加载xml配置文件方式获取Spring容器, 是通过ClassPathXmlApplicationContext类