Spring Profiles and @Profile

1. Overview

Profiles are a core feature of the framework — allowing us to map our beans to different profiles — for example, dev, test, and prod.

How to set Profiles for Spring
How to active Profiles in Spring
How to get active Profiles in Spring


Profiles in Spring Boot

Spring Boot supports all the profile configuration outlined so far, with a few additional features.

1. Activating or Setting a Profile

# 方式1: 配置文件里配置
spring.profiles.active=dev

# 方式2:使用SpringApplication
SpringApplication.setAdditionalProfiles("dev");

# 方式3:
# Set profiles using Maven in Spring Boot
<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <profiles>
                <profile>dev</profile>
            </profiles>
        </configuration>
    </plugin>
    ...
</plugins>
# and execute the Spring Boot-specific Maven goal:
mvn spring-boot:run

2. Profile-specific Properties Files

The most important profiles-related feature that Spring Boot brings is profile-specific properties files. These have to be named in the format application-{profile}.properties.

For example, we can configure different data sources for dev and production profiles by using two files named application-dev.properties and application-production.properties:

# In the application-production.properties file, we can set up a MySql data source:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=root
spring.datasource.password=root

# In the application-dev.properties file, to use an in-memory H2 database:
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

In this way, we can easily provide different configurations for different environments.

3. Multi-Document Files

Club all the properties in the same file and use a separator to indicate the profile
Starting version 2.4, We can specify the dev and production properties in the same application.properties:

my.prop=used-always-in-all-profiles
#---
spring.config.activate.on-profile=dev
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=root
spring.datasource.password=root
#---
spring.config.activate.on-profile=production
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

This file is read by Spring Boot in top to bottom order.

参考:Spring Profiles

你可能感兴趣的:(框架,spring,java,jvm)