Setting "Active Profile" through Class AbstractAnnotationConfigDispatcherServletInitializer?

spring, spring-data, spring-mvc

Solution

Depending which contexts' profiles you want to set, one way to do it is to override the

AbstractAnnotationConfigDispatcherServletInitializer#createRootApplicationContext()

and

AbstractAnnotationConfigDispatcherServletInitializer#createServletApplicationContext()

to set the active profiles in there. For example

@Override
protected WebApplicationContext createRootApplicationContext() {
    WebApplicationContext context = (WebApplicationContext)super.createRootApplicationContext();
    ((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles("profiles");
    return context;
}

Note the `super` call. You'll want this so that the super implementation actually creates the `WebApplicationContext` from your `@Configuration` classes (or any context you specified).

Problem

How would you set the "active profile" property when extending the class AbstractAnnotationConfigDispatcherServletInitializer ?

Original source