小编典典

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

spring

我们使用spring 3.1的新环境配置文件功能。当前,我们通过在将应用程序部署到的服务器上设置环境变量spring.profiles.active = xxxxx来设置活动配置文件。

我们认为这是次优的解决方案,因为我们要部署的war文件应该只具有一个附加的属性文件,该文件设置了应加载spring应用上下文的环境,因此部署不依赖于服务器上设置的某些环境变量。

我试图弄清楚该怎么做,发现:

ConfigurableEnvironment.setActiveProfiles()

我可以使用它来以编程方式设置配置文件,但是我仍然不知道在何时何地执行此代码。春天的环境在哪里加载?我可以从属性文件中加载要传递给方法的参数吗?

更新:我只是在docs上找到了可以设置活动配置文件的工具?


阅读 472

收藏
2020-04-12

共2个答案

小编典典

只要可以在web.xml中静态提供配置文件名称,或者使用新的无XML配置类型(配置文件可以通过编程方式从属性文件中加载配置文件)。

当我们仍然使用XML版本时,我进一步进行了调查,发现了以下不错的解决方案,你在其中实现了自己的解决方案,你ApplicationContextInitializer只需将带有属性文件的新PropertySource添加到源列表中以搜索特定于环境的配置设置。在下面的示例中,可以spring.profiles.activeenv.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>
2020-04-12
小编典典

in web.xml

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>profileName</param-value>
</context-param>

使用 WebApplicationInitializer
当你web.xml在Servlet 3.0环境中没有文件并且完全从Java启动Spring 时,可以使用这种方法:

class SpringInitializer extends WebApplicationInitializer {

    void onStartup(ServletContext container) {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.getEnvironment().setActiveProfiles("profileName");
        rootContext.register(SpringConfiguration.class);
        container.addListener(new ContextLoaderListener(rootContext));
    }
}

SpringConfiguration用注释类的地方@Configuration

2020-04-12