Close

Spring MVC - Setting Active Profile

[Updated: Oct 31, 2018, Created: Oct 31, 2018]

Following example shows how to set Environment active profile in Spring MVC.

In servlet based application, we need to add following in web.xml:

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>profile1</param-value>
</context-param>

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

Java Config

@Configuration
@ComponentScan
public class AppConfig extends WebMvcConfigurationSupport {
}

Web initializer

public class MyWebInitializer implements WebApplicationInitializer {

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

src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>prod</param-value>
    </context-param>
</web-app>

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 - Setting Active Profile Select All Download
  • spring-mvc-setting-active-profile
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • web.xml

    See Also