我们使用 spring 3.1 的新环境配置文件功能。我们目前通过在部署应用程序的服务器上设置环境变量 spring.profiles.active=xxxxx 来设置事件配置文件。
我们认为这是一个次优的解决方案,因为我们要部署的 war 文件应该只有一个额外的属性文件,它设置 spring 应用程序上下文应该加载的环境,因此部署不依赖于设置的某些 env var服务器。
我试图弄清楚如何做到这一点并发现:
ConfigurableEnvironment.setActiveProfiles()
我可以使用它以编程方式设置配置文件,但我仍然不知道何时何地执行此代码。 Spring 上下文加载的地方?我可以从属性文件加载我想传递给方法的参数吗?
更新:我刚刚在 docs 找到我可以实现哪个来设置事件配置文件?
最佳答案
在 web.xml
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>profileName</param-value>
</context-param>
使用 WebApplicationInitializer
当您在 Servlet 3.0 环境中没有 web.xml
文件并且完全从 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
进行注释。
关于spring - 如何通过属性文件而不是通过 env 变量或系统属性设置事件 spring 3.1 环境配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8587489/