一、@Configuration 和 @Component 区别
1.1 @Configuration介绍
@Configuration
用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
@Configuration
的内部实现如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration { ... }
由上代码可看到,@Configuration
的内部实现核心就是@Component
注解,而且@Configuration
注解看起来只不过是@Component
注解的一个别名,那么我们是否也能在配置类中使用@Component
注解呢?
1.2 两个注解的区别
@Configuration
标记的方法会被包装成CGLIB的wrapper,其工作原理是:如果方式是首次被调用那么原始的方法体会被执行并且结果对象会被注册到Spring上下文中。之后所有的对该方法的调用仅仅只是从Spring上下文中取回该对象返回给调用者。
而由@Component
标注的方法在每次程序请求方法返回的Bean都会执行一次方法体,故返回的是不同的对象实例。
一般情况下,我们需要保证对象的唯一性,故在配置类中最好使用@Configuration
注解。不过,若使用@Component
注解也有办法保证对象的唯一,只是步骤比较繁琐。还是推荐使用@Configuration
注解。
1.3 实例
package com.dxz.demo.configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestMain {
public static void main(String[] args) {
// @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
// 如果加载spring-context.xml文件:
// ApplicationContext context = new
// ClassPathXmlApplicationContext("spring-context.xml");
//获取bean
SimpleBeanConsumer sb1= (SimpleBeanConsumer) context.getBean("simpleBeanConsumer");
SimpleBeanConsumer sb2= (SimpleBeanConsumer) context.getBean("simpleBeanConsumer");
if(sb1==sb2) System.out.println("true");
else System.out.println("false");
}
}
这代码会像我们期望的一样正常运行,并且返回true。因为new SimpleBeanConsumer(simpleBean())这段代码中simpleBean()方法会由Spring代理执行,Spring发现方法所请求的Bean已经在容器中,那么就直接返回容器中的Bean。所以全局只有一个SimpleBeanConsumer对象的实例。
这段代码会返回false。在执行new SimpleBeanConsumer(simpleBean()) 时simpleBean()不会被Spring代理,会直接调用simpleBean()方法获取一个全新的SimpleBean对象实例所以全局会有多个SimpleBeanConsumer对象的实例。
要修正第二段代码中的问题,可以使用@Autowired如下所示: