↗ JetBrains 20% discount
Buy any product from JetBrains and get a 20% discount.
In Spring MVC, we can set active profile programmatically in our WebApplicationInitializer implementation.
WebApplicationInitializer
package com.logicbig.example; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; public interface GreetingService { String getGreetingMsg(); @Service @Profile("default") class LocalGreetingService implements GreetingService { @Override public String getGreetingMsg() { return "hi from local environment"; } } @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"; } } }
package com.logicbig.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class ExampleController { @Autowired private GreetingService greetingService; @GetMapping("/") @ResponseBody public String handle() { return greetingService.getGreetingMsg(); } }
package com.logicbig.example; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{AppConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } @Override public void onStartup(ServletContext servletContext) throws ServletException { super.onStartup(servletContext); servletContext.setInitParameter("spring.profiles.active", "dev"); } }
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
$ curl -s "http://localhost:8080/"hi from dev
Dependencies and Technologies Used:
Version compatibilities of spring-webmvc with this example:
Versions in green have been tested.