一、配置类的优点
前面的几篇文章中的案例虽然用到注解进行对象创建、属性注入,但是还没有实现全注解开发。现在可以使用配置类来代替xml文件,简化开发,实现全注解。
二、具体实现
(1)创建类
@Component
public class Department {
@Value(value = "1")
private Long id;
@Value(value = "张三")
private String name;
public Department() {
}
public Department(Long id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
(2)创建配置类(配置类会被IOC容器实例化)
//@Configuration可以不加,下面解释
@Configuration
//开启组件扫描
@ComponentScan(basePackages = {"com.wsh.pojo"})
public class SpringConfig {
}
(3)JAVA程序
public void test(){
//读取配置类中的配置
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
Department department = context.getBean("department", Department.class);
System.out.println(department.toString());
}
输出
Department{id=1, name='张三'}
三、@Configuration
(1)该注解有一个属性proxyBeanMethods,其默认值为true。
(2)当proxyBeanMethods为true时,该对象是一个代理对象,则调用该类中的方法时,调用的是经过加强的原有方法(加强后每次得到的对象是同一个)。(Full模式)
@Configuration
public class SpringConfig {
}
public void test(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
SpringConfig bean = context.getBean(SpringConfig.class);
System.out.println(bean);
}
com.wsh.config.SpringConfig$$EnhancerBySpringCGLIB$$5d8a0756@1e730495
(3)当proxyBeanMethods为false时或者该配置类没有加上@Configuration时,该对象不是代理对象。(Lite模式)
com.wsh.config.SpringConfig@27d415d9
(4)代理对象的好处:在IOC初始化后,如果调用注解了@Bean的方法,则会从IOC容器中获取该对象;如果不是代理对象,则每次调用执行原方法new一个对象。
public class Demo1 {
public Demo1() {
System.out.println("Demo1");
}
}
@Configuration
public class SpringConfig {
@Bean
public Demo1 demo1(){
return new Demo1();
}
}
public void test(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
SpringConfig bean = context.getBean(SpringConfig.class);
System.out.println(bean);
bean.demo1();
bean.demo1();
}
Demo1
com.wsh.config.SpringConfig$$EnhancerBySpringCGLIB$$d5ef9e59@56de5251
上面的案例调用注解了@Bean的方法,会从IOC容器中找到对象并返回,而不是执行原方法来new一个对象。
当proxyBeanMethods为false时或者该配置类没有加上@Configuration时,每次调用注解了@Bean的方法会执行原方法来new一个对象。
Demo1
com.wsh.config.SpringConfig@1c72da34
Demo1
Demo1