第六课springboot实现不同环境配置加载方式一

编程

第六课:springboot实现不同环境配置加载方式一

  • 简介
  • 项目的结构
  • 代码内容
    • 1.pom文件
    • 2.properties文件中的内容

  • 实现的流程

简介

简单的项目中,我们可能会遇到将本地的代码打包发版到不同的环境中去;但是不同的环境的properties里面的配置的属性或者value 值可能并不相同;但是我们打包的时间就可能需要在同一个application.properties文件中根据不同环境去注释掉别的环境的配置;打开本环境的配置;然后打包发版 这样做起了无疑是比较麻烦的而且容易出现错误; 当前案例是最简答的区分环境的的主要针对的是只有一个properties文件的
项目demo下载

项目的结构


如上图 springboot 默认使用的application.properties文件;
然后根据不同的环境创建了 不同的.properties文件内容;
application-dev.properties --> 指向的是dev 的环境
application-local.properties --> 指向的是local 的环境
application-prod.properties --> 指向的是prod 的环境

代码内容

1.pom文件

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

<!--含有多个main 需要指定某一个启动class-->

<start-class>com.khy.ApplicationMain</start-class>

</properties>

<dependencies>

<!-- Spring Boot Web 依赖 -->

<dependency>

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

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

</dependency>

</dependencies>

<build>

<resources>

<resource>

<directory>src/main/resources</directory>

<excludes>

<exclude>**/*.properties</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> <!-- 是否替换@xx@表示的maven properties属性值 --> <filtering>true</filtering> <includes> <include>application.properties</include> <include>application-${profiles.active}.properties</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <profiles> <profile> <id>local</id> <properties> <profiles.active>local</profiles.active> </properties> <activation> <!--默认生效的配置组--> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>dev</id> <properties> <profiles.active>dev</profiles.active> </properties> </profile> <profile> <id>prod</id> <properties> <profiles.active>prod</profiles.active> </properties> </profile> </profiles>

主要是通过maven 的profiles 标签;通过项目在打包
mvn clean install -Dmaven.test.skip=true -P dev 标识选择的是dev换的包内容;

2.properties文件中的内容


上面是所有的properties文件的中的配置内容;

实现的流程

这种实现方式是springboot 最简单的根据不同的maven打包指定加载properties文件内容;
只是需要将不同环境的properties文件修改成项目中的指定的文件名内容;然后再application.properties文件中指定
spring.profiles.active = @profiles.active@
这个需要在项目的pom 文件中去配置对应的信息内容
然后使用maven 打包的时间通过指定不同环境的properties文件然后启动项目的端口就是指定文件中设置的

以上是 第六课springboot实现不同环境配置加载方式一 的全部内容, 来源链接: utcz.com/z/518084.html

回到顶部