Spring MVC配置文件的三個常用配置詳解


  Spring MVC項目中通常會有二個配置文件,sprng-servlet.xml和applicationContext.xml二個配置文件,通常會出現以下幾個配置

  1. <context:annotation-config />

  它的作用是隱式地向 Spring 容器注冊  AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor 這4個BeanPostProcessor。其作用是如果你想在程序中使用注解,就必須先注冊該注解對應的類,如下圖所示:

依賴的類 注解
CommonAnnotationBeanPostProcessor @Resource 、@PostConstruct、@PreDestroy
PersistenceAnnotationBeanPostProcessor的Bean @PersistenceContext
AutowiredAnnotationBeanPostProcessor Bean @Autowired
RequiredAnnotationBeanPostProcessor @Required

  當然也可以自己進行注冊:

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

  2. <context:component-scan base-package="com.*" >

     <context:component-scan/> 配置項不但啟用了對類包進行掃描以實施注釋驅動 Bean 定義的功能,同時還啟用了注釋驅動自動注入的功能(即還隱式地在內部注冊了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor),因此當使用 <context:component-scan/> 后,就可以將 <context:annotation-config/> 移除了

     在這里有一個比較有意思的問題,就是掃描是否需要在二個配置文件都配置一遍,我做了這么幾種測試:

            

  (1)只在applicationContext.xml中配置如下

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

  啟動正常,但是任何請求都不會被攔截,簡而言之就是@Controller失效

  (2)只在spring-servlet.xml中配置上述配置

  啟動正常,請求也正常,但是事物失效,也就是不能進行回滾

  (3)在applicationContext.xml和spring-servlet.xml中都配置上述信息

  啟動正常,請求正常,也是事物失效,不能進行回滾

  (4)在applicationContext.xml中配置如下

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

  在spring-servlet.xml中配置如下

<context:component-scan base-package="com.sohu.login.web" />

  此時啟動正常,請求正常,事物也正常了。

  結論:在spring-servlet.xml中只需要掃描所有帶@Controller注解的類,在applicationContext中可以掃描所有其他帶有注解的類(也可以過濾掉帶@Controller注解的類)。

  3. <mvc:annotation-driven />

  它會自動注冊DefaultAnnotationHandlerMapping 與AnnotationMethodHandlerAdapter


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM