Thomasz 的回答是有效的,只要配置文件名称可以在 web.xml 中静态提供,或者使用新的无 XML 配置类型,可以以编程方式加载配置文件以从属性文件中设置。
由于我们仍然使用 XML 版本,我进一步调查并发现了以下不错的解决方案,您可以在其中实现自己的解决方案,ApplicationContextInitializer
您只需将带有属性文件的新 PropertySource 添加到源列表中以搜索特定于环境的配置设置。在下面的示例中,可以在文件中设置spring.profiles.active
属性。env.properties
public class P13nApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private static Logger LOG = LoggerFactory.getLogger(P13nApplicationContextInitializer.class);
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
try {
environment.getPropertySources().addFirst(new ResourcePropertySource("classpath:env.properties"));
LOG.info("env.properties loaded");
} catch (IOException e) {
// it's ok if the file is not there. we will just log that info.
LOG.info("didn't find env.properties in classpath so not loading it in the AppContextInitialized");
}
}
}
然后,您需要将该初始化程序作为参数添加到ContextLoaderListener
spring 中,如下所示web.xml
:
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>somepackage.P13nApplicationContextInitializer</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
您还可以将其应用于DispatcherServlet
:
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextInitializerClasses</param-name>
<param-value>somepackage.P13nApplicationContextInitializer</param-value>
</init-param>
</servlet>