spring boot:基於profile的多環境配置(spring boot 2.3.4)


一,為什么要進行多環境配置?

1,沒有人會在生產環境中進行開發和測試,

所以通常會有多個環境的划分:

工程師本地的開發環境

進行測試的測試環境

最終上線的生產環境

每個環境對應不同的數據庫/緩存等數據源和不同的接口

如果每次部署應用時都需要修改配置文件則會很不方便,

我們通過設置切換profile,可以使應用在不同的環境中調用相應的配置文件工作

 

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/

說明:作者:劉宏締 郵箱: 371125307@qq.com

 

二,演示項目的相關信息

1,項目地址:

https://github.com/liuhongdi/profile

 

2,功能說明:

           演示了通過切換profile讀取配置文件的屬性

 

3,項目結構;如圖:

 

 

三,配置文件說明

1,pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

 

2,application.properties

custom.orig="application.properties"
custom.active="application.properties"
spring.profiles.active=dev

說明:spring.profiles.active用來指定默認使用的一個配置文件

 

3,application-prd.properties

custom.active="application-prd.properties"

 

4,application-dev.properties

custom.active="application-dev.properties"

 

四,java代碼說明

1,HomeController.java

@Controller
@RequestMapping("/home")
public class HomeController {

    //讀取變量custom.orig
    @Value("${custom.orig}")
    private String origstr;
    
    //讀取變量custom.active
    @Value("${custom.active}")
    private String activestr;
    
    //打印從配置文件中讀取到的變量值
    @GetMapping("/home")
    @ResponseBody
    public String home() {
        return "this is home/home page<br/> active:"+activestr+"<br/>  orig:"+origstr;
    }
}

 

五,測試效果:

1,打包:

 

 先執行clean

然后執行:package

 

2,測試執行:

從控制台執行:

[root@localhost profile]# java -jar target/demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=prd

然后訪問頁面:

http://127.0.0.1:8080/home/home

返回:

this is home/home page
active:"application-prd.properties"
orig:"application.properties"

可以看到當前application.properties和application-prd.properties都生效,

而兩者中均存在的同名的變量生效的是application-prd.properties

 

3,修改profile為dev:

[root@localhost profile]# java -jar target/demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

返回:

this is home/home page
active:"application-dev.properties"
orig:"application.properties"

這次是application-dev生效

 

4,測試不指定profile

[root@localhost profile]# java -jar target/demo-0.0.1-SNAPSHOT.jar 

返回:

this is home/home page
active:"application-dev.properties"
orig:"application.properties"

說明spring.profiles.active=dev指定默認的配置文件已生效

 

六,查看spring boot版本

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.4.RELEASE)

 


免責聲明!

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



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