天天看點

SpringMvc配置之<context:annotation-config />

當我們需要使用BeanPostProcessor時,直接在Spring配置檔案中定義這些Bean顯得比較笨拙,例如:

  使用@Autowired注解,必須事先在Spring容器中聲明AutowiredAnnotationBeanPostProcessor的Bean:

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

使用 @Required注解,就必須聲明RequiredAnnotationBeanPostProcessor的Bean:

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

  類似地,使用@Resource、@PostConstruct、@PreDestroy等注解就必須聲明 CommonAnnotationBeanPostProcessor;使用@PersistenceContext注解,就必須聲明 PersistenceAnnotationBeanPostProcessor的Bean。

  這樣的聲明未免太不優雅,而Spring為我們提供了一種極為友善注冊這些BeanPostProcessor的方式,即使用<context:annotation- config/>隐式地向 Spring容器注冊AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor這4個BeanPostProcessor。如下:

<context:annotation-config/>       

  另,在我們使用注解時一般都會配置掃描包路徑選項:

<context:component-scan base-package="pack.pack"/>      

  該配置項其實也包含了自動注入上述processor的功能,是以當使用<context:component-scan/>後,即可将<context:annotation-config/>省去。

備注:

在配置檔案中使用 context 命名空間之前,必須在 <beans> 元素中聲明 context 命名空間。

<?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.springframework.org/schema/beans"
        <strong>xmlns:context="http://www.springframework.org/schema/context"</strong>  
    ...
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
               http://www.springframework.org/schema/context  
               http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    ...
        <strong><context:annotation-config/></strong>
    </beans>
           

繼續閱讀