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

标签 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>

但是,我仍然得到这个错误:

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/

相关文章:

Spring Boot Gradle 添加 Native 库失败(java.lang.UnsatisfiedLinkError)

Spring Security登录页面与loginProcessingURL

angularjs - 服务器从包含#(哈希)符号的 AngularJs 页面重定向到登录 URL

spring - 如何根据需要标记 Spring MVC 参数

java - 在执行遗留代码的 java jvm 中发生了什么,该代码因语言更改而失效

java - 简单的java线程测试程序不起作用

java - 如何检查字符串是否包含允许的字符

java - 如何摆脱 "HHH90000003: Use of DOM4J entity-mode is considered deprecated"

java - SonarQube 在 Spring Framework Controller 和 Spring Framework 应用程序主类中显示安全错误

Java Spring MVC 如何获取这个设定值?