Spring MVC框架的高级配置
http://tech.ddvip.com 2006年11月21日 社区交流
本文详细介绍Spring MVC框架的高级配置
由于与applicationContext.xml相比,主机配置不需如此频繁地进行更改,因此下一步便是将主机配置移动到web.xml文件中(如果可能的话)。幸运的是,我们有一个可用的解决方案。看一下下面关于web.xml配置的片断:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-somehost.com.xml
</param-value>
</context-param>
正如您所看到的,除了web.xml文件中常有的ContextLoaderListener之外,我们还添加了contextConfigLocation上下文参数配置。这一参数用于指示框架查找这些配置文件的位置。如果这一参数被省略,则Spring就只能到applicationContext.xml中查找。这里我们也定义了特定于主机的配置文件来使用。
利用这种方法,我们将所有特定于主机的配置从applicationContext.xml文件中移除,这样便减轻了其在不同应用程序部署中的同步性。
如果这种方法成为您的新习惯,您还可以使其更加灵活。通过遵守下列指令,也可以将特定于主机的配置从web.xml文件中移除。
为此,需要创建特定于我们的应用程序上下文的类:
package net.nighttale.spring.util;
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};
}
}
}
这个类拓展了Spring中常被作为默认值使用的XmlWebApplicationContext。XmlWebApplicationContext类将Web应用程序的配置从XML定义文件中复制过来。默认情况下,它可以配置来自applicationContext.xml和[servlet-name]-servlet.xml文件中的应用程序。这个类执行的惟一一项额外任务便是获取它所在的主机名称,并将applicationContext-[hostname].xml文件添加到配置文件列表中。
来源:bea 作者:Dejan Bosanac 责编:豆豆技术应用