In Spring MVC, we can set active profile programmatically in our WebApplicationInitializer implementation.
Example
Environment related beans
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";
}
}
}
Example Controller
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();
}
}
Web Initializer
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");
}
}
Running
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
Output
Curl Output $ curl -s "http://localhost:8080/" hi from dev
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 3.2.9.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- JDK 25
- Maven 3.9.11
|