如何解决通过 spring.profiles.active
我在通过 spring.profiles.active
属性指定活动配置文件来覆盖默认应用程序属性时遇到问题。
我开发了一个示例项目来重现这个问题。 我有 2 个 application.yml 文件:
application-default.yml
spring:
profiles:
active: local
test:
value: "This is the test value for application properties of default"
application-local.yml
test:
value: "This is the test value for application properties of local"
然后我开发了一个组件来打印测试值:
@Component
public class TestComponent {
@Value("${test.value}")
private String testValue;
@PostConstruct
public void postConstruct() {
System.out.println(testValue);
}
}
这段代码的输出是:
2021-01-07 16:19:01.080 INFO 335505 --- [ main] com.test.Application : The following profiles are active: local
This is the test value for application properties of default
2021-01-07 16:19:01.419 INFO 335505 --- [ main] com.test.Application : Started Application in 0.944 seconds (JVM running for 1.441)
我预计输出将是:
This is the test value for application properties of local
我知道使用 application.yml
而不是 application-default.yml
可以按预期工作,但我的目标是使用 application.yml
来保存所有配置文件共有的基本属性并指定特定于环境的配置通过使用配置文件。
我使用的是 spring-boot 2.4.0,build.gradle
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation group: 'org.springframework.boot',name: 'spring-boot-starter',version: '2.4.0'
}
为什么这个属性不被覆盖?
解决方法
这是由于 spring boot 加载属性的顺序引起的。
使用活动配置文件和所有配置文件的通用属性创建 application.yml 文件,并从 application-default.yml
中删除 spring.profiles.active 属性。
spring:
profiles:
active: local
您也可以像这样在运行时选择活动配置文件
java -jar example.jar --spring.profiles.active=local
,
默认属性文件应该被称为 application.yml 而不是 application-default.yml
尝试重命名它,它应该可以正常工作..在此处阅读更多内容
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。