简体   繁体   中英

How can I set active profile via annotation in spring?

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)

You can pass in the active profile(s) at runtime using the spring.profiles.active property:

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

See the SpringSource blog post on the introduction of profiles.

If you are using making a standalone application or web application you pass active profile these way, according to Spring blog

Activation in Web application

<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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM