栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何通过属性文件而不是通过环境变量或系统属性设置活动的Spring 3.1环境配置文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何通过属性文件而不是通过环境变量或系统属性设置活动的Spring 3.1环境配置文件

只要可以在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");        }    }}

然后,你需要将该初始值设定项作为ContextLoaderListenerspring 的参数添加,如下所示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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/387116.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号