首页 文章

Spring Boot配置优先级

提问于
浏览
1

我正在开发一个新项目并首次使用Spring-Boot .

传统上,当使用Spring和属性文件进行配置时,我在分发(WAR)中提供了默认属性,并允许在某些记录的位置覆盖它们 .

例如:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:app.properties</value>
            <value>file:${user.home}/.company/app/app.properties</value>
        </list>
    </property>
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="ignoreResourceNotFound" value="true" />
</bean>

这将允许我们重新部署应用程序而不会丢失本地系统配置 .

在阅读documentation on this for Spring-Boot之后,"application.properties"中的任何内容似乎都会获得更高的优先级,并覆盖使用@PropertySource注释指定的任何内容 .

我喜欢Spring,因为它允许我们坚持惯用,这让我感到担心我可能已经做了级联错误的属性 .

什么是最合适的方式来提供外部化属性,包括在分发中的合理默认值(嵌入式数据库,简单身份验证等)?

此外,如果有人知道,我很想知道Spring-Boot中属性顺序背后的原因 .

Note

我已经尝试过查看SpringApplication.setDefaultProperties,但似乎无法找到从何处获取SpringApplication对象的引用 . main方法在其上调用一个静态方法(run),当捆绑为WAR文件时,它永远不会实际运行 . 这样做也似乎有点黑客攻击 .

1 回答

  • 4

    SpringApplication 是一个公共类,因此您可以在运行应用程序之前创建实例并设置其属性(静态 run() 方法只是方便) . 您也可以使用 SpringApplicationBuilder ,这是您在外部容器中运行时作为回调获得的内容 . 使用这些API,您可以设置默认属性和配置文件,包括 application.properties 文件的位置( spring.config.location )和名称( spring.config.name ) .

    请注意(根据您提供的链接),您还可以在容器中使用JNDI变量来覆盖或设置环境属性 . 如果要将多个应用程序打包到同一个JVM中,这也可能很有用 .

相关问题