springboot 使用spring.profiles.active 区分不同环境下配置文件

转自:https://blog.51cto.com/4923168/2177950

一、新建一个maven 工程

image.png

二、在pom.xml文件中加入如下依赖

<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">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.bt.com.cn</groupId>

  <artifactId>bt-springboot</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <name>bt-springboot</name>

  <description>bt-springboot</description>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.0.5.RELEASE</version>

</parent>

<!-- Add typical dependencies for a web application -->

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

</dependencies>

<!-- Package as an executable jar -->

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>

三、在src/main/resources下新建如下文件

image.png

内容分别

application-dev.properties

image.png

application-prd.properties

image.png

application-test.properties

image.png

appliction.properties

image.png

其中application.properties中spring.profiles.active=prd  prd 为上面想要读文件的后一部分文件名

四、编写启动类

package com.batian;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class App {

public static void main(String[] args) {

SpringApplication.run(App.class, args);

}

}

四、编写一个controller

package com.batian.controller;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class HttpController {

@Value("${httpUrl}")

private String httpUrl;

@RequestMapping("/getHttpUrl")

public String getHttpUrl(){

return httpUrl;

}

}

五、分别修改application.properties中spring.profiles.active=prd 

1、当spring.profiles.active=prd  执行结果如下

image.png

2.当spring.profiles.active=test

image.png

3、当spring.profiles.active=dev

image.png

此时已实现不同环境下读取不同的配置文件

原文地址:https://www.cnblogs.com/sharpest/p/13709812.html