@Configuration
从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
xml版
- 编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String name;
private Integer age;
}
- 配置xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="Person" class="cn.jbit.bean.Person">
<property name="age" value="18"></property>
<property name="name" value="zhangsan"></property>
</bean>
</beans>
- 测试
@Test
public void test01(){
ClassPathXmlApplicationContext cpx = new ClassPathXmlApplicationContext("beans.xml");
Person bean = cpx.getBean("Person",Person.class);
System.out.println(bean);
}
注解版
- 编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String name;
private Integer age;
}
- 编写测试类
//配置类 == 配置文件
@Configuration //告诉spring这是一个配置类
public class MainConfig {
// 给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
@Bean("PS") //给id起别名
public Person person(){
return new Person("lisi",20);
}
}
- 测试
@Test
public void test02(){
ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);
Person bean = app.getBean(Person.class);
System.out.println(bean);
// 获取bean的id名字
String[] beanNamesForType = app.getBeanNamesForType(Person.class);
for (String name : beanNamesForType) {
System.out.println(name);
}
}