Spring配置项<context:component-scan/>和<context:annotation-config/>

<context:annotation-config/>

这是一条向Spring容器中注册

AutowiredAnnotationBeanPostProcessor

CommonAnnotationBeanPostProcessor

PersistenceAnnotationBeanPostProcessor

RequiredAnnotationBeanPostProcessor

这4个BeanPostProcessor.注册这4个BeanPostProcessor的作用,就是为了你的系统能够识别相应的注解。

那么哪些注释依赖这些Bean呢。

如果想使用 @Resource、@PostConstruct、@PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor。 
如果想使用 @PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessor的Bean。 
如果想使用 @Autowired注解,那么就必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。 
如果想使用 @Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。

同样,传统的声明方式如下: 

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/> 

但是,就一般而言,这些注解我们是经常使用,比如Antowired,Resuource等注解,如果总是按照传统的方式一条一条的配置,感觉比较繁琐和机械。于是Spring给我们提供了<context:annotation-config/>的简化的配置方式。

注意:即使你使用了<context:annotation-config/>注解,以@Autowired为例,对于需要注入的Bean,仍然还要在xml中手动声明。这样很不方便,因此就引出了下面的<context:component-scan>注解。

<context:component-scan>

<context:component-scan>首先有和<context:annotation-config/>一样的作用,此外,它还可以扫描指定包下的类,将拥有注解的它们注册到Spring容器中。

综上,也就是说,如果用<context:annotation-config/>,我们还需要配置Xml注册Bean,而使用<context:component-scan />的话,注册的步骤都免了,当然前提是我们对需要扫描的类使用的注解(比如@Componet,@Service),而如果同时使用两个配置的话,<context:annotation-config/>会被忽略掉。

猜你喜欢

转载自www.cnblogs.com/darknebula/p/9975886.html