15

How can I set active profile via annotation in 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)

4

2 回答 2

12

spring.profiles.active您可以使用以下属性在运行时传入活动配置文件:

-Dspring.profiles.active="profile1,profile2"

有关配置文件的介绍,请参阅SpringSource 博客文章。

于 2013-06-26T08:58:25.520 回答
8

根据Spring 博客,如果您正在使用制作独立应用程序或 Web 应用程序,您可以通过这些方式传递活动配置文件

在 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>

使用手动创建的上下文激活

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles("dev");
ctx.load("classpath:/com/bank/config/xml/*-config.xml");
ctx.refresh();
于 2013-06-26T08:50:46.650 回答