springboot怎么读取不同yml配置文件
我配置了三个文件夹,dev、prod、test 代表三个不同的环境配置文件,
然后通过最外层的application.yml来加载不同文件夹的配置文件,
其中system.yml的配置为:
system:config: "dev-env"
application-dev.yml为:
#启动端口配置server:
port: 8085
#spring配置
spring:
application:
name: multi-env #应用名
但是通过
@Value("${system.config}")public String config;
报错
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'system.config' in value "${system.config}"
但是可以读取application-dev.yml的配置值
@Value("${server.port}")public String config;
最外层的application.yml用于动态切换环境
spring:profiles:
active: ${profiles.active}
pom.xml配置
<build><plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<!--使用默认的变量分割符即${}-->
<configuration>
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</plugin>
</plugins>
<!-- 测试文件的编译路径设置 -->
<testResources>
<testResource>
<!--这里是关键! 根据不同的环境,把对应文件夹里的配置文件打包-->
<directory>src/main/resources</directory>
<includes>
<include>application.yml</include>
</includes>
<filtering>true</filtering>
</testResource>
<testResource>
<!--这里是关键! 根据不同的环境,把对应文件夹里的配置文件打包-->
<directory>src/main/resources/${profiles.active}</directory>
<includes>
<include>**/*.yml</include>
</includes>
<filtering>false</filtering>
</testResource>
</testResources>
<resources>
<resource>
<!--打包该目录下的 application.yml -->
<directory>src/main/resources</directory>
<includes>
<include>application.yml</include>
</includes>
<!-- 启用过滤 即该资源中的变量将会被过滤器中的值替换 -->
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<!-- ${profiles.active}由profile提供 -->
<directory>src/main/resources/${profiles.active}</directory>
<includes>
<include>**/*.yml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<!-- 定义 filter,即该资源中的值将会用来替换同名属性(设置 filtering 为 true 的资源中的属性)-->
<filters>
<filter>
src/main/resources/${profiles.active}/application-${profiles.active}.yml
</filter>
</filters>
</build>
<profiles>
<profile>
<!-- 本地开发环境 -->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
</profile>
<profile>
<!-- 生产环境 -->
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
</properties>
</profile>
</profiles>
回答
把文件夹去掉就可以了
以上是 springboot怎么读取不同yml配置文件 的全部内容, 来源链接: utcz.com/a/36687.html