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

 

此時已實現不同環境下讀取不同的配置文件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM