Close

Spring MVC - Setting Active Profiles Programmatically

[Last Updated: Oct 31, 2018]

In Spring MVC, we can set active profile programmatically in our WebApplicationInitializer implementation.

Example

Environment related beans

public interface GreetingService {
    String getGreetingMsg();

    @Service
    @Profile("dev")
    class DevGreetingService implements GreetingService {

        @Override
        public String getGreetingMsg() {
            return "hi from dev";
        }
    }

    @Service
    @Profile("prod")
    class ProductionGreetingService implements GreetingService {

        @Override
        public String getGreetingMsg() {
            return "hi from production";
        }
    }
}

Example Controller

@Controller
public class ExampleController {
  @Autowired
  private GreetingService greetingService;

  @RequestMapping("/")
  @ResponseBody
  public String handle() {
      return greetingService.getGreetingMsg();
  }
}

Web Initializer

public class MyWebInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) {
      AnnotationConfigWebApplicationContext ctx =
              new AnnotationConfigWebApplicationContext();
      ctx.getEnvironment().setActiveProfiles("dev");
      ctx.register(AppConfig.class);
      ctx.setServletContext(servletContext);
      ServletRegistration.Dynamic servlet =
              servletContext.addServlet("springDispatcherServlet",
                      new DispatcherServlet(ctx));
      servlet.setLoadOnStartup(1);
      servlet.addMapping("/");
  }
}

Running

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 5.1.2.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • JDK 1.8
  • Maven 3.5.4

Spring MVC - Programmatically Setting Active Profiles Select All Download
  • spring-mvc-setting-active-profile-programmatically
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyWebInitializer.java

    See Also