我所处的情况需要将具有某些属性的文件(最终包含 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.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)
作为类中使用的自定义属性具有更高的优先级。
来自 Spring Boot 文档:
72.3 Change the location of external properties of an application
A nice way to augment and modify this is to add @PropertySource annotations to your application sources. Classes passed to the SpringApplication static convenience methods, and those added using setSources() are inspected to see if they have @PropertySources, and if they do, those properties are added to the Environment early enough to be used in all phases of the ApplicationContext lifecycle. Properties added in this way have lower priority than any added using the default locations (e.g. application.properties), system properties, environment variables or the command line.
这个优先级是有意义的,因为您可以在运行时提供的配置(例如 application.properties
)应该始终能够覆盖应用程序中“硬编码”的配置。
To test this mechanism, I created a test project,
要测试类或行为,您应该编写单元测试。
您可以使用其中一种方法来覆盖 application.properties
值:
重命名
test.properties
进入application.properties
并将其移至src/test/resources
.使用
@TestPropertySource
。来自javadoc:
Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application declaratively via @PropertySource or programmatically
关于java - 为什么当 application.properties 存在时不使用 @PropertySource ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48518765/