yml配置:
spring:
profiles:
active: @activatedProperties@
pom.xml环境:
<profiles>
<!-- 本地环境 -->
<profile>
<id>dev</id>
<activation>
<!-- 默认激活dev -->
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<activatedProperties>dev</activatedProperties>
<jar.name>xxxxx</jar.name>
</properties>
</profile>
<!-- 生产环境 -->
<profile>
<id>pro</id>
<properties>
<activatedProperties>pro</activatedProperties>
<jar.name>xxxxx</jar.name>
</properties>
</profile>
</profiles>
现象及错误解决:
项目启动时报错说不能使用‘@’符号,根据网上的步骤将@activatedProperties@使用单引号括起来
spring:
profiles:
active: '@activatedProperties@'
结果:被当成字符串处理,引用未生效
springboot在启动的时候会识别当前环境,用引号之后识别的是一串字符串"@activatedProperties@",而下面才是我们需要的"dev"
Activated activeProfiles dev
2020-01-08 16:34:19.803 DEBUG 4256 --- [ main] .c.l.ClasspathLoggingApplicationListener : Application started with classpath: [file:/C:/Java/jdk1.8.0_141/jre/lib/charsets.jar......
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.1.RELEASE)
2020-01-08 16:34:19.848 INFO 4256 --- [ main] Application : Starting ArgusServerApplication on XD021NB1911015a with PID 4256......
2020-01-08 16:34:19.848 INFO 4256 --- [ main] Application : The following profiles are active: dev
2020-01-08 16:34:19.849 DEBUG 4256 --- [ main] o.s.boot.SpringApplication : Loading source class Application
2020-01-08 16:34:19.878 DEBUG 4256 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Activated activeProfiles dev
原因发现:
springboot项目如果没有直接继承SpringBoot即定义parent关系,pom.xml如下代码
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
</parent>
而是如下方式
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
</dependency>
则不能暴露配置,需要在build标签内添加如下配置即可
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>application-${activatedProperties}.yml</include>
<include>application.yml</include>
</includes>
</resource>
</resources>