Spring MVC框架的高級配置

這篇文章裏面說的東西,其實很多都是比較簡單的。它的重點在於對於Spring的配置文件applicationContext.xml如何來管理。因爲如果把它加入到源代碼管理(CVS或Subversion等)中,則對此文件的頻繁更改會造成源代碼管理的混亂。
一種解決方法是使用配置文件來保存特定的信息,比如數據庫的連接信息。這種方式爲大多數人所知道,關鍵在於使用PropertyPlaceholderConfigurer。
另外一種做法就是把原來的applicationContext.xml進行拆分,這種方式也應用廣泛。一種方式就是添加import:<import resource=”applicationContext-somehost.com.xml”/>;另外的方式就是在web.xml中使用contextConfigLocation來指定使用的配置文件名稱。
如果不想修改web.xml話,可以編寫自己的XmlWebApplicationContext的子類,由它來指定加載某些特定的配置文件。比如下面的例子:
import java.net.InetAddress;
import org.springframework.web.context.support.XmlWebApplicationContext;
public class PerHostXmlWebApplicationContext
extends XmlWebApplicationContext {

protected String[] getDefaultConfigLocations() {
String hostname = “localhost”;
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
}

String perHostConfiguration = DEFAULT_CONFIG_LOCATION_PREFIX
+ “applicationContext-”
+ hostname
+ DEFAULT_CONFIG_LOCATION_SUFFIX
;

logger.debug(
“Adding per host configuration file: ”
+ perHostConfiguration
);

if (getNamespace() != null) {
return new String[] {
DEFAULT_CONFIG_LOCATION_PREFIX
+ getNamespace()
+ DEFAULT_CONFIG_LOCATION_SUFFIX
, perHostConfiguration};
}
else {
return new String[] {
DEFAULT_CONFIG_LOCATION
, perHostConfiguration};
}
}
}
在配置文件web.xml中,可以這樣寫:
<context-param>
<param-name>contextClass</param-name>
<param-value>
net.nighttale.spring.util.PerHostXmlWebApplicationContext
</param-value>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章