【问题标题】:Spring application does not see files with properties extension (except application.properties)Spring 应用程序看不到带有属性扩展名的文件(application.properties 除外)
【发布时间】:2020-03-18 23:34:00
【问题描述】:

我正在开发一个 Spring Boot Web 应用程序,它需要从 homepage.properties 文件中获取一些数字数据。

但是,thymeleaf 模板视图不会呈现除 application.properties 以外的文件的任何属性,即使 .properties 文件位于同一个文件夹中。

src > main > resources > application.properties(获取属性成功)

src > main > resources > homepage.properties(不获取属性)

这是一个简单的用法:

application.properties

working.hours=650

homepage.properties

test.hours=30

index.html

<h1 class="lan_fun_value mb-1" th:text="${@environment.getProperty('working.hours)}"></h1> //renders 650
<h1 class="lan_fun_value mb-1" th:text="${@environment.getProperty('test.hours)}"></h1> //renders nothing

任何想法可能是什么问题?

【问题讨论】:

  • 你为什么相信它读取homepage.properties文件?您是否告诉 Spring 加载该文件?也许您应该阅读文档描述如何分配环境属性:docs.spring.io/spring-boot/docs/2.2.1.RELEASE/reference/html/…。 --- #14 描述了application.properties 默认加载。 #16 描述了如何使homepage.properties 被加载。另请阅读第 2.3 节。应用程序属性文件。

标签: java spring spring-boot properties thymeleaf


【解决方案1】:

您可以使用@PropertySources 加载多个属性文件。您可以在应用程序类上方编写以下代码。

@SpringBootApplication
@PropertySources({
        @PropertySource("application.properties"),
        @PropertySource("homepage.properties")
})
public class Application{

}

您必须在working.hourstest.hours 之后添加单引号。

【讨论】:

  • 完全忘记了我必须先注册它们,因为 application.properties 是默认的。感谢您的解决方案!
【解决方案2】:

您可以通过@PropertySource("homepage.properties")直接添加

或者直接通过@Value注入

@Value( "${test.hours=30}")
private String testHours;

或者如果你在 spring 中使用 xml:

<context:property-placeholder location="application.properties, homepage.properties"/>

或者在你命令运行你的应用程序时将它作为参数传递。

【讨论】:

    猜你喜欢
    • 2016-01-20
    • 2018-03-10
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多