【问题标题】:Spring-Boot-Starter-Parent in combination with "property-placeholder" in XML-based Spring configurationSpring-Boot-Starter-Parent 结合基于 XML 的 Spring 配置中的“property-placeholder”
【发布时间】:2017-05-03 14:07:09
【问题描述】:

在我的 POM 中,我继承自 Spring Boot 的“spring-boot-starter-parent”:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
</parent>

根据以下Spring Boot documentationSpring Boot Parent 将 maven-resources-plugin 的默认过滤器令牌从 ${maven.token} 更改为 @maven.token@ 以防止与 Spring 风格的占位符发生冲突。背景:Spring 的分隔符与 Maven 的分隔符相同。

据我了解:更改会影响 Maven 属性,而不是 Spring 属性扩展。但也许我错了,反之亦然?

现在,在通过以下方式导入的基于 XML 的 Spring 应用程序上下文配置文件中使用“context:property-placeholder”时:

@Configuration
@ImportResource("spring/applicationContext-core.xml")
@EnableJpaRepositories
@EnableAutoConfiguration
public class StudyDayApplication {

    /**
     * This main is for using Spring Boot in case of a JAR file packaging.
     * 
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(StudyDayApplication.class, args);
    }
}

Spring 特定键的属性扩展不再起作用。在我的“application-core.xml”中,我使用特定于 Spring 的“property-placeholder”来使用外部化配置属性。但我仍然想使用 Spring 特定的属性分隔符(例如,在我的“dataSource”bean 中扩展“jpa.driver.classname”)。

...
<context:property-placeholder
        ignore-resource-not-found="false"
        location="classpath*:*.properties"/>
...
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
    <property name="driverClassName" value="${jpa.driver.classname}"/>
...

但 Spring 中的替换仅在将“${jpa.driver.classname}”替换为“@jpa.driver.classname@”时才有效

根据following remark添加以下XML属性时:

order="1"
ignore-unresolvable="true"

对于“property-placeholder”,我在 Spring Boot 启动期间没有收到任何异常告诉我:

"无法解析字符串值中的占位符 'jpa.driver.classname' "${jpa.driver.classname}"

但我确信属性扩展无法正常工作,因为“属性占位符”会忽略无法解析的项目。当 bean 将使用非扩展的属性键实例化时,它会导致稍后出现异常。仅设置“order=1”属性也无济于事。

也许,Spring Boot 不需要明确地使用“property-placeholder”作为Spring Boot searches for "application.properties" automatically within the application。但我不想改用这种方法。

有没有办法使用“spring-boot-starter-parent”并保持典型的 Spring 属性扩展处​​于活动状态?

【问题讨论】:

    标签: spring-boot property-placeholder


    【解决方案1】:

    我发现了我的问题 :-) 引起这种奇怪效果的不是 Spring,而是我的配置。

    问题是:属性文件不在类路径的根文件夹中,而是在下面。并且只要不加载属性文件,就不能执行属性扩展。

    要查找所有 *.properties 文件 - 即使在子目录中,也必须使用 ANT 样式的符号:

    <context:property-placeholder
            ignore-resource-not-found="false"
            location="classpath*:**/*.properties"/>
    

    小心:根据这个定义,所有“*.properties”文件都位于 JAR 文件和类路径根目录的任何子文件夹中。最后,它们被合并到一个单一的属性文件中。所以,内存消耗可能会增加!

    更多详情请分别咨询Spring documentationfollowing comment @stackoverflow.com

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 2018-12-10
      • 1970-01-01
      • 2022-07-30
      • 2017-08-03
      • 2019-12-26
      • 2018-09-26
      • 2020-05-23
      • 2018-12-15
      相关资源
      最近更新 更多