In Spring MVC, we can set active profile programmatically in our WebApplicationInitializer implementation.
WebApplicationInitializer
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"; } } }
@Controller public class ExampleController { @Autowired private GreetingService greetingService; @RequestMapping("/") @ResponseBody public String handle() { return greetingService.getGreetingMsg(); } }
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("/"); } }
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Dependencies and Technologies Used: