使用占位符时无法导入属性值

ray*_*man 3 java spring spring-mvc spring-boot

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

但是,我仍然收到此错误:

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)
Run Code Online (Sandbox Code Playgroud)

PropertiesLoaderSupport在这个方法中在类中添加了一个断点:

public void setLocations(Resource... locations) {
    this.locations = locations;
}
Run Code Online (Sandbox Code Playgroud)

我注意到这个方法多次调用,其中一个我注意到填充的位置参数:

URL [file:/d:/etc/services/pushExecuterService/pushExecuterServices.properties]
Run Code Online (Sandbox Code Playgroud)

但是,我仍然收到此错误.

  • 我仔细检查了我的项目,我没有任何额外的PropertyPlaceholderConfigurer bean(没有检查外部依赖项)

  • 我用硬编码运行我的应用程序我在spring-boot日志中可以看到xml中的params:

    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]`
    
    Run Code Online (Sandbox Code Playgroud)

所以我不确定发生了什么.任何线索?

谢谢.

Raf*_*iec 5

Spring Boot支持基于Java的配置.为了添加配置属性,我们可以将@PropertySource注释与@Configuration注释一起使用.

属性可以存储在任何文件中.可以使用@Value注释将属性值直接注入bean:

@Configuration
@PropertySource("classpath:mail.properties")
public class MailConfiguration {
    @Value("${mail.protocol}")
    private String protocol;
    @Value("${mail.host}")
    private String host;
}
Run Code Online (Sandbox Code Playgroud)

@ PropertySource的value属性指示要加载的属性文件的资源位置.例如,"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