context:annotation-config
他的作用是向 Spring 容器注册
- AutowiredAnnotationBeanPostProcessor
- CommonAnnotationBeanPostProcessor
- PersistenceAnnotationBeanPostProcessor
- RequiredAnnotationBeanPostProcessor
注册这4个BeanPostProcessor的作用,就是为了你的系统能够识别相应的注解。
例如:
- 如果你想使用@Autowired注解,那么就必须事先在 Spring容器中声明AutowiredAnnotationBeanPostProcessorBean。传统声明方式如下:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>
- 如果想使用@ Resource 、@ PostConstruct、@PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor
- 如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessor的Bean
- 如果想使用 @Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean.同样,传统声明方式如下:
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
一般来说,这些注解我们还是比较常用,尤其是Antowired的注解,在自动注入的时候更是经常使用,所以如果总是需要按照传统的方式一条一条配置显得有些繁琐和没有必要,于是spring给我们提供<context:annotation-config/>
的简化配置方式,自动帮你完成声明。但是它仅仅是用于激活那些已经在spring容器里注册过的bean(无论是通过xml的方式还是通过package sanning的方式)上面的注解;
context:component-scan
除了具有<context:annotation-config>
的功能之外,<context:component-scan>
还可以在指定的package下扫描以及注册javabean;比如我们自己写的javabean。
总之:
<context:annotation-config />
仅能够在已经在已经注册过的bean上面起作用。对于没有在spring容器中注册的bean,它并不能执行任何操作。
<context:component-scan>
除了具有<context:annotation-config />
的功能之外,还具有自动将带有@component,@service,@Repository等注解的对象注册到spring容器中的功能。所以我们一般用context:component-scan,当使用 <context:component-scan/>
后,就可以将 <context:annotation-config/>
移除了
或者可以这么理解:
启用使用注解装配(@Autowired,@Inject,0的@Resource) 有助于完全消除Spring配置中的<property>
和<constructor-arg>
,我们仍需要使用<bean>
元素显示定义Bean
如:
public class Instrumentalist implements Performer{
/**注入乐器*/
@Autowired
private Instrument instrument;
public void perform() throws Exception {
...
}
}
配置文件如下配置,不需要在kenny中加入property属性指定instrument;自动byName匹配名为instrument这个bean
<bean id="kenny" class="org.spring.zhuanpeiBean.Instrumentalist"/>
<bean id="instrument"class="org.spring.zhuanpeiBean.Saxophone"/>
context:component-scan除了具有context:annotation-config功能外,还允许Spring 自动检测Bean和定义Bean,这意味着不适用<bean>
元素,Spring应用中大多数(或者所有)Bean都能实现定义和装配;
以上例子的配置文件中如果使用的context:component-scan后就不必要再配置instrument这个bean了