在一個大的專案結構,Spring bean配置檔位於不同的檔夾以便於維護和模組化。例如,Spring-Common.xml在common 檔夾中,Spring-Connection.xml 在connection檔夾,Spring-ModuleA.xml在ModuleA 檔夾等等。
你可以加載多個Spring bean的配置檔如下代碼中:
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml", "Spring-Connection.xml","Spring-ModuleA.xml"});
把所有的 Spring XML 檔放入在專案類路徑中。
project-classpath/Spring-Common.xml project-classpath/Spring-Connection.xml project-classpath/Spring-ModuleA.xml
解決方法
以上方法是缺乏組織並且很容易出錯,更好的辦法應組織所有的Spring bean 配置檔到一個XML檔。例如,創建一個Spring-All-Module.xml檔,並導入整個Spring bean的檔如下:
File : Spring-All-Module.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <import resource="common/Spring-Common.xml"/> <import resource="connection/Spring-Connection.xml"/> <import resource="moduleA/Spring-ModuleA.xml"/> </beans>
現在,可以加載一個這樣的 XML 檔:
ApplicationContext context = new ClassPathXmlApplicationContext(Spring-All-Module.xml);
將這個檔放入專案的類路徑。
project-classpath/Spring-All-Module.xml
注意
在Spring3,所述替代解決方案是使用 JavaConfig @Import.
在Spring3,所述替代解決方案是使用 JavaConfig @Import.
上一篇:
如何注入值到Spring bean屬性
下一篇:
Spring內部bean實例