Spring boot结合Maven实现不同环境的配置

配置文件层次:

Spring boot结合Maven实现不同环境的配置

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.yanwu.www</groupId>
<artifactId>Spring-Env</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>example</name>
<url>http://maven.apache.org</url> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies> <profiles>
<profile>
<!-- 本地开发环境 -->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 测试环境 -->
<id>sit</id>
<properties>
<profiles.active>sit</profiles.active>
</properties>
</profile>
<profile>
<!-- 生产环境 -->
<id>pro</id>
<properties>
<profiles.active>pro</profiles.active>
</properties>
</profile> </profiles> <build>
<filters>
<filter>src/main/resources/env/${profiles.active}/application.yml</filter>
</filters>
<!-- 替换${key}内容 -->
<resources>
<resource>
<filtering>true</filtering>
<!--要到达最底层目录-->
<directory>src/main/resources/env/${profiles.active}</directory>
</resource>
</resources>
</build> </project>

带有${key}的配置文件:

/Spring-Env/src/main/resources/application.yml

 #激活的环境配置
spring:
profiles:
active: ${spring.profiles.active}
#端口
server:
port: ${server.port}

配置文件一:

src/main/resources/env/pro/application.yml

 server:
port: 8083
env: pro ftp: hello pro spring:
profiles:
active: pro

配置文件二:

src/main/resources/env/dev/application.yml

 server:
port: 8084 ftp: hello dev spring:
profiles:
active: dev

配置文件三:

src/main/resources/env/sit/application.yml

 server:
port: 8082
env: sit
ftp: hello sit spring:
profiles:
active: sit

运行Spring boot主程序即可实现!

测试程序:

 @RestController
public class SampleController { @Autowired
private Environment env; @RequestMapping("/sample")
public String sample(){ return "spring boot success ! and profile is ==>"+
env.getProperty("spring.profiles.active")+"=====>"+
env.getProperty("ftp");
}
}

maven打包:

mvn clean install -P pro

Spring boot结合Maven实现不同环境的配置

maven打包:

mvn clean install -P sit

Spring boot结合Maven实现不同环境的配置

注:maven打包也可以使用eclipse的maven插件

Spring boot结合Maven实现不同环境的配置

上一篇:SQL Server 2012 自动增长列,值跳跃问题


下一篇:09 jdk1.5的并发容器:ConcurrentHashMap