[JAVA] Switch environment with Spring Boot application.properties and @Profile annotation

Overview

--Switch profile and execute with Spring Boot --If no profile is specified, Spring Framework uses the default profile. --Prepare three profiles of your own: development, test, production --test and production are configured to use the same element in part --Prepare application-*. Properties for each profile and use the described value --Use @Profile annotation to DI (Dependency injection) the bean class object corresponding to the specified profile. --Prepare bean classes for multiple profiles --Corresponds to the case where multiple profiles are specified

Source code list

$ tree src
src
├── main
│   ├── java
│   │   └── info
│   │       └── maigo
│   │           └── lab
│   │               └── sample
│   │                   └── profiles
│   │                       ├── MyData.java
│   │                       ├── MyDataForDefault.java
│   │                       ├── MyDataForDevelopment.java
│   │                       ├── MyDataForTestAndProduction.java
│   │                       ├── MyRestController.java
│   │                       └── ProfilesApplication.java (← This time, the contents are omitted)
│   └── resources
│       ├── application-development.properties
│       ├── application-production.properties
│       ├── application-test.properties
│       └── application.properties

Source code of the basic part

MyRestController.java

Inject MyData objects with the DI function of Spring Framework. Write the @Autowired annotation in the instance variable myData. Return MyData information in JSON when accessing http: // localhost: 8080 /.

package info.maigo.lab.sample.profiles;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {

    @Autowired
    private MyData myData;

    @RequestMapping("/")
    public MyData index() {
        return myData;
    }
}

MyData.java

Interface definition for MyData object. No method is prepared this time.

package info.maigo.lab.sample.profiles;

public interface MyData {
}

MyDataForDefault.java

The implementation class of MyData used in the default profile. You can specify the profile when DI with @Profile annotation. Here, default is specified. Assign the string "default" to the instance variable profile. Assign message.value of application.properties to the instance variable message.

package info.maigo.lab.sample.profiles;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("default")
public class MyDataForDefault implements MyData {

    public String profile = "default";

    @Value("${message.value}")
    public String message;
}

application.properties

The property file used by the default profile.

message.value=Hello, default!

Start with default profile

Specify the JAR file created by building and start it. There is no parameter to specify the profile.

$ java -jar target/profiles-0.0.1-SNAPSHOT.jar

When you access the started server, you can see that the information of the default profile is loaded.

$ curl http://localhost:8080/
{"profile":"default","message":"Hello, default!"}

Source code used in the development profile

MyDataForDevelopment.java

The implementation class of MyData used in the development profile. Specify the develop profile with @Profile annotation. Assign the string "development" to the instance variable profile. Assign message.value of application-development.properties to the instance variable message.

package info.maigo.lab.sample.profiles;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("development")
public class MyDataForDevelopment implements MyData {

    public String profile = "development";

    @Value("${message.value}")
    public String message;
}

application-development.properties

Property files used in the development profile.

message.value=Hello, development!

Start by specifying the development profile

Specify development in the JVM parameter -Dspring.profiles.active.

$ java -Dspring.profiles.active=development -jar target/profiles-0.0.1-SNAPSHOT.jar

When you access the started server, you can see that the development profile information is loaded.

$ curl http://localhost:8080/
{"profile":"development","message":"Hello, development!"}

Source code used in test and production profiles

MyDataForTestAndProduction.java

The MyData implementation class used in the test and production profiles. Test and production are specified in the @Profile annotation. Objects of this class are subject to DI when any of the specified profiles is specified. The JSON profile returned by @RestController is generated by the getProfile method of this class. You can get multiple profile names specified by Environment # getActiveProfiles.

package info.maigo.lab.sample.profiles;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
@Profile({"test", "production"})
public class MyDataForTestAndProduction implements MyData {

    @Autowired
    private Environment env;

    public String getProfile() {
        return String.join(",", env.getActiveProfiles());
    }

    @Value("${message.value}")
    public String message;
}

application-test.properties

Property file used in the test profile.

message.value=Hello, test!

application-production.properties

Property files used in the production profile.

message.value=Hello, production!

Start by specifying the test profile

Specify test for the JVM parameter -Dspring.profiles.active.

$ java -Dspring.profiles.active=test -jar target/profiles-0.0.1-SNAPSHOT.jar

When you access the started server, you can see that the test profile information is loaded.

$ curl http://localhost:8080/
{"message":"Hello, test!","profile":"test"}

Start by specifying the production profile

Specify production in the JVM parameter -Dspring.profiles.active.

$ java -Dspring.profiles.active=production -jar target/profiles-0.0.1-SNAPSHOT.jar

When you access the started server, you can see that the production profile information is loaded.

$ curl http://localhost:8080/
{"message":"Hello, production!","profile":"production"}

Launch with multiple profiles test and production

Specify multiple profiles "test, production" separated by commas in the JVM parameter -Dspring.profiles.active.

$ java -Dspring.profiles.active=test,production -jar target/profiles-0.0.1-SNAPSHOT.jar

When you access the started server, you can see that the profile information of both test and production is read because the value of the profile item contains "test, production".

$ curl http://localhost:8080/
{"message":"Hello, production!","profile":"test,production"}

The value of message.value defined in application-test.properties and application-production.properties is the result of the conflict. The value of application-production.properties is prioritized (it is considered that the value to be conflicted should not be set). ..

When I tried to specify "production, test" in the reverse order of profile specification, the value of application-test.properties was prioritized.

$ java -Dspring.profiles.active=production,test -jar target/profiles-0.0.1-SNAPSHOT.jar
$ curl http://localhost:8080/
{"message":"Hello, test!","profile":"production,test"}

Perhaps the profile you specify later will take precedence (overwrite?).

This environment

Reference material

Recommended Posts

Switch environment with Spring Boot application.properties and @Profile annotation
Spring profile function, and Spring Boot application.properties
Switch environment by boot argument with SpringBoot
HTTPS with Spring Boot and Let's Encrypt
Spring Boot environment construction with Docker (January 2021 version)
About designing Spring Boot and unit test environment
Build Spring Boot project by environment with Gradle
Create Spring Boot environment with Windows + VS Code
Create a Spring Boot development environment with docker
Spring boot development-development environment-
Download with Spring Boot
Try using DI container with Laravel and Spring Boot
[Java] [Spring Boot] Specify runtime profile --Spring Boot starting with NetBeans
Spring Security usage memo: Cooperation with Spring MVC and Boot
Spring Boot with Spring Security Filter settings and addictive points
SSO with GitHub OAuth in Spring Boot 1.5.x environment
How to boot by environment with Spring Boot of Maven
Attempt to SSR Vue.js with Spring Boot and GraalJS
Database environment construction with Docker in Spring boot (IntellJ)
Connect Spring Boot and Angular type-safely with OpenAPI Generator
[Spring Boot] Environment construction (macOS)
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Docker × Spring Boot environment construction
Add module with Spring Boot
Getting Started with Spring Boot
Create microservices with Spring Boot
Send email with spring boot
Spring Boot for annotation learning
Change the injection target for each environment with Spring Boot 2
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Implement REST API with Spring Boot and JPA (Application Layer)
Implement REST API with Spring Boot and JPA (Infrastructure layer)
Until INSERT and SELECT to Postgres with Spring boot and thymeleaf
Connect to database with spring boot + spring jpa and CRUD operation
Implement REST API with Spring Boot and JPA (domain layer)
Domain Driven Development with Java and Spring Boot ~ Layers and Modules ~
Various switching application.properties for each environment when Spring Boot starts
Easily develop web applications with STS and Spring Boot. In 10 minutes.
Use Basic Authentication with Spring Boot
◆ Spring Boot + gradle environment construction memo
gRPC on Spring Boot with grpc-spring-boot-starter
Set Spring profile when executing bootRun task with Spring Boot Gradle Plugin
Create an app with Spring Boot 2
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Get validation results with Spring Boot