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



我正在使用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;
}

注意到此方法多次调用,在其中一个中,我注意到填充了以下位置参数:

URL [file:/d:/etc/services/pushExecuterService/pushExecuterServices.properties]

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

  • 我仔细检查了我的项目,但我没有任何额外的属性占位符配置器豆(没有检查外部依赖项)

  • 我运行我的应用程序时,对我可以在 Spring 启动日志中看到的 xml 中的参数进行了硬编码:

    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注释直接注入到 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

最新更新