【发布时间】:2018-07-09 04:21:49
【问题描述】:
我所处的情况需要将具有一些属性的文件(最终包含 ID 和电子邮件地址列表)映射到 HashMap。在 Spring 中,我发现可以使用 @ConfigurationProperties 和 @PropertySource 将属性文件映射到对象。为了测试这种机制,我创建了一个测试项目,但是当默认的application.properties 文件存在时,@PropertySource 似乎被忽略了。我想知道这怎么可能以及如何解决它以便它使用指定的属性文件。
Application.java
@SpringBootApplication
@EnableConfigurationProperties
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
DemoProperties.java
@Component
@Configuration
@ConfigurationProperties("test")
@PropertySource("classpath:test.properties")
public class DemoProperties {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
test.properties
test.name=myNameGood
application.properties
test.name=myNameBad
ApplicationTests.java
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
DemoProperties demoProperties;
@Test
public void contextLoads() {
System.out.println(demoProperties.getName());
}
}
因此,当存在application.properties 时,此测试会打印myNameBad,但是当我删除或重命名该文件时,输出为myNameGood(这是所需的)。
【问题讨论】:
-
它不会被忽略。它被覆盖。如果两者中的属性相同,则 application.properties 中的属性具有更高的优先级。尝试添加不同名称的变量并检查
-
@pvpkiran 更改变量有效,但我仍然不明白为什么它在我的示例中被覆盖。那么指定属性源有什么意义呢?
-
@ConfigurationProperties仅适用于 Spring boot 加载的属性,即来自默认application.properties和朋友的属性。它不适用于使用@PropertySource加载的属性,这些属性稍后在进程中加载,@ConfigurationProperties在此之前绑定。
标签: java spring properties mapping