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)
原文地址:https://www.cnblogs.com/architectforest/p/13717656.html