我正在使用 Spring Boot。
我在类路径外的外部文件中声明了属性。
我将其添加到我的一个 XML 文件中:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>file:///d:/etc/services/pushExecuterService/pushExecuterServices.properties</value>
</list>
</property>
</bean>
但是,我仍然得到这个错误:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'configuration.serviceId' in string value "${configuration.serviceId}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
我在此方法的 PropertiesLoaderSupport
类中添加了一个断点:
public void setLocations(Resource... locations) {
this.locations = locations;
}
我注意到这个方法被调用了多次,其中一次我注意到 locations 参数填充了:
URL [file:/d:/etc/services/pushExecuterService/pushExecuterServices.properties]
但是,我仍然收到此错误。
我仔细检查了我的项目,我没有任何额外的 PropertyPlaceholderConfigurer bean(没有检查外部依赖项)
我运行我的应用程序时对 xml 中的参数进行了硬编码,我可以在 spring-boot 日志中看到:
2015-01-05 18:56:52.902 INFO 7016 --- [ main] o.s.b.f.c.PropertyPlaceholderConfigurer: Loading properties file from URL [file:/d:/etc/services/pushExecuterService/pushExecuterServices.properties]`
所以我不确定发生了什么。有线索吗?
谢谢。
最佳答案
Spring Boot 支持基于 Java 的配置。为了添加配置属性,我们可以将@PropertySource 注释与@Configuration 注释一起使用。
属性可以存储在任何文件中。可以使用 @Value 注释将属性值直接注入(inject)到 bean 中:
@Configuration
@PropertySource("classpath:mail.properties")
public class MailConfiguration {
@Value("${mail.protocol}")
private String protocol;
@Value("${mail.host}")
private String host;
}
@PropertySource 的值属性指示要加载的属性文件的资源位置。例如,“classpath:/com/myco/app.properties”或“file:/path/to/file”
但 Spring Boot 提供了一种使用属性的替代方法,允许强类型 bean 管理和验证应用程序的配置:@ConfigurationProperties
请参阅此博客文章,其中包含使用 @ConfigurationProperties 的示例:http://blog.codeleak.pl/2014/09/using-configurationproperties-in-spring.html
对于@PropertySource 示例,您可以查看这篇文章:http://blog.codeleak.pl/2014/09/testing-mail-code-in-spring-boot.html
关于java - 使用占位符时无法导入属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27784261/