web.xml中定義的Spring的XML配置檔案啟動順序
阿新 • • 發佈:2019-02-20
在web.xml中定義的Spring的配置檔案一般有兩個:
1、Spring上下文環境的配置檔案:applicationContext.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
2、SpringMVC配置檔案:spring-servlet.xml
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value >classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
載入順序是:首先載入Spring上下文環境配置檔案,然後載入SpringMVC配置檔案,並且如果配置了相同的內容,SpringMVC配置檔案會被優先使用。
所以這裡需要注意一個問題,一定要注意SpringMVC配置檔案內容不要把Spring上下文環境配置檔案內容覆蓋掉。
比如在Spring上下文環境配置檔案中先引入service層,然後又加入了事務:
<context:component-scan base-package="com.acms.service"></context:component-scan>
<!-- define the transaction manager -->
<bean id="transactionManagerOracle"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourceOracle" />
</bean>
<tx:annotation-driven transaction-manager="transactionManagerOracle" />
但是在SpringMVC配置檔案中卻預設引入所有類(當然也包括service層),但是沒有加入事務
<context:component-scan base-package="com.acms"></context:component-scan>
那麼這時事務功能是無法起作用的,也就是程式碼中加入@Transactional註解是無效的。
所以為了防止這種問題一般是在Spring上下文配置檔案中引入所有的類,並且加上事務:
<context:component-scan base-package="com.acms"></context:component-scan>
<!-- define the transaction manager -->
<bean id="transactionManagerOracle"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourceOracle" />
</bean>
<tx:annotation-driven transaction-manager="transactionManagerOracle" />
而在SpringMVC配置檔案中只引入controller層:
<context:component-scan base-package="com.acms.controller" />
<context:component-scan base-package="com.acms.*.controller" />
Men were born to be suffering, the pain of struggle, or the pain of regret?