1、通过spring.profiles.active切换
1、创建springboot的web项目
2、编辑配置文件
application.yml
spring:
profiles:
active: dev
application-dev.yml
com:
name: dev-wuyu
application-pro.yml
com:
name: pro-wuyu
3、编写测试类
@RestController
public class TestController {
@Value("${com.name}")
private String name;
@GetMapping("/test")
public String test() {
return "hello,"+name;
}
}
4、测试
①、运行前打开application.yml,将dev改为pro,通过浏览器访问可以看到属性的变化
②、将项目打成jar包,然后运行时指定配置文件
java -jar swdl-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev -Dspring.config.location=application-dev.yml
-spring.profiles.active:指定环境,即文件后缀
-Dspring.config.location:指定具体的文件名
2、通过打包的方式切换
1、修改pom.xml文件
<profiles>
<!-- 本地开发环境 -->
<profile>
<!--执行打包命令时将使用此处的id进行定位 -->
<id>dev</id>
<properties>
<!--此处为对应的环境放置配置文件的目录,上一步创建的为dev,这里设置为dev。下面两个目录配置参照此处 -->
<env>dev</env>
</properties>
<activation>
<!--此处将dev设置为默认环境 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 测试环境 -->
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<!-- 生产环境 -->
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<build>
<resources>
<!--此处的设置是打包的时候排除不相关的目录 -->
<resource>
<!--此处设置为上面在resources目录下创建的文件夹 -->
<directory>src/main/resources/env</directory>
<excludes>
<exclude>dev/*</exclude>
<exclude>test/*</exclude>
<exclude>prod/*</exclude>
</excludes>
<!--开启过滤器,此处不能忽略! -->
<filtering>true</filtering>
</resource>
<!--此处的设置是为了将放置于resources文件夹下mybatis的mapper文件正常打包进去,和一些不需要多环境的配置文件 -->
<resource>
<!--如果将mybatis的mapper文件放在dao接口的同目录下,应该将此处设置为src/main/java -->
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
</includes>
<!--此处不需要过滤器过滤 -->
<filtering>false</filtering>
</resource>
<!--此处设置是配置相应配置文件夹的路径 -->
<resource>
<directory>src/main/resources/env/${env}</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!--这里写上main方法所在类的路径 -->
<configuration>
<mainClass>com.study.changeenv1.ChangeEnvApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2、编写三个配置文件
3、编写测试类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Value("${com.name}")
private String name;
@GetMapping("/test")
public String test() {
return "hello,"+name;
}
}
4、打包
在项目的pom.xml文件夹中,使用mvn package -Ptest进行打包,其中-P指定对应的环境进行打包