java 如何在 spring 中通过注释设置活动配置文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17315379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I set active profile via annotation in spring?
提问by Malahov
How can I set active profile via annotation in spring ?
如何在 spring 中通过注释设置活动配置文件?
For example:
例如:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ApplicationConfig.class }, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles( profiles = {ApplicationProfiles.TEST} )
public class CacheManagerTest {
...
}
For JUnit test this works perfect, but how can I init production application context ? (I do not have any main method/сlasses)
对于 JUnit 测试,这很完美,但是我如何初始化生产应用程序上下文?(我没有任何主要方法/课程)
回答by Jonathan
You can pass in the active profile(s) at runtime using the spring.profiles.active
property:
您可以在运行时使用以下spring.profiles.active
属性传入活动配置文件:
-Dspring.profiles.active="profile1,profile2"
See the SpringSource blog poston the introduction of profiles.
有关配置文件的介绍,请参阅SpringSource 博客文章。
回答by Grzegorz ?ur
If you are using making a standalone application or web application you pass active profile these way, according to Spring blog
根据Spring 博客,如果您正在使用制作独立应用程序或 Web 应用程序,您可以通过这些方式传递活动配置文件
Activation in Web application
在 Web 应用程序中激活
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>production</param-value>
</init-param>
</servlet>
Activation with manually created context
使用手动创建的上下文激活
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles("dev");
ctx.load("classpath:/com/bank/config/xml/*-config.xml");
ctx.refresh();