Spring Boot中的Profile文件

目录

 

 

理论

演示


 

理论

Profile是Spring对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境:

1. 多profile文件形式:

格式:application-{profile}.properties

application-dev.properties、application-prod.properties

2. yml中文件块模式:

server:
  port: 8085
spring:
  profiles:
    active: aaa
---

server:
  port: 8089
spring:
  profiles: aaa

---

server:
  port: 8083
spring:
  profiles: prod

3. 激活方式:

          命令行:--spring.profiles.active=dev

          配置文件:spring.profiles.active=dev

          jvm参数:Dspring.profiles.active=dev

 

 

 

演示

首先演示properties文件:

程序结构如下:

Spring Boot中的Profile文件_第1张图片

源码如下:

ProfileApplication.java

package com.profiledemo.profile;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProfileApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProfileApplication.class, args);
    }

}

application.properties

server.port=8080
spring.profiles.active=prod

application-dev.properties

server.port=8081

application-prod.properties

server.port=80

运行截图如下:

可见prod生效了!

 

使用yml文件:把所有的properties的都注释掉。

程序结构如下:

Spring Boot中的Profile文件_第2张图片

application.yml

server:
  port: 8085
spring:
  profiles:
    active: aaa
---

server:
  port: 8089
spring:
  profiles: aaa

---

server:
  port: 8083
spring:
  profiles: prod

运行截图如下:

Spring Boot中的Profile文件_第3张图片

 

通过虚拟机和指定激活profile位置

profile位置:

--spring.profiles.active=dev

Spring Boot中的Profile文件_第4张图片

虚拟机:

-Dspring.profiles.active=dev

Spring Boot中的Profile文件_第5张图片

 

打包后可以使用命令行的方式操作:

java -jar xxx.jar --spring.profiles.active=dev

Spring Boot中的Profile文件_第6张图片

你可能感兴趣的:(Java,Spring,Boot)