[JAVA] Switching beans by profile annotation in Spring

Use the spring profile mechanism to switch between dynamically injected beans.

For the time being, create a suitable spring-boot project.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


Create an appropriate interface and create some implementation classes for it.

public interface ProfileSample {
	String getValue();
public class DefaultProfile implements ProfileSample {

	public String getValue() {
		return "default";


The default value for profile is `` `default```. Therefore, if you specify that value in profile annotation, this class will be used when profile is not specified.

public class DevProfile implements ProfileSample {

	public String getValue() {
		return "dev";

public class ProductionProfile implements ProfileSample {

	public String getValue() {
		return "production";


Inject the interface created above into the startup class.

public class SampleController {

	ProfileSample sample;

	String home() {
		return "Hello World!";

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SampleController.class, args);

After that, if you specify the spring.profiles.active property somewhere, that profile will be used, and if it is not specified, `` `default``` will be used as mentioned above.

The profile specification looks like this with command line arguments.


When specifying in a property file, for example application.yaml, it looks like this.


spring.profiles.active: production

By the way, there are many ways to specify properties, so for the list and priority, see https://docs.spring.io/spring-boot/docs/2.0.0.M4/reference/htmlsingle/#boot-features-external-config

For the contents of this example, the default method of interface may be sufficient.

Recommended Posts

Switching beans by profile annotation in Spring
Until custom validation by annotation is implemented in Spring Framework and message is output
Switch environment with Spring Boot application.properties and @Profile annotation
Inject Logger in Spring
Use Interceptor in Spring
Microservices in Spring Cloud
Get cookies in Spring
Dynamically access the property specified by the string in Spring BeanWrapper