使用 Spring 表达式语言访问属性文件 [英] Accessing properties file in Spring Expression Language
问题描述
我使用 Spring Boot 使用 Thymeleaf 创建了一个简单的 Web 应用程序.我使用 application.properties 文件作为配置.我想要做的是向该文件添加名称和版本等新属性,并从 Thymeleaf 访问值.
I created a simple web application with Thymeleaf using Spring Boot. I use the application.properties file as configuration. What I'd like to do is add new properties such as name and version to that file and access the values from Thymeleaf.
我已经能够通过创建一个新的 JavaConfiguration 类并公开一个 Spring Bean 来实现这一点:
I have been able to achieve this by creating a new JavaConfiguration class and exposing a Spring Bean:
@Configuration
public class ApplicationConfiguration {
@Value("${name}")
private String name;
@Bean
public String name() {
return name;
}
}
然后我可以像这样使用 Thymeleaf 在模板中显示它:
I can then display it in a template using Thymeleaf like so:
<span th:text="${@name}"></span>
这对我来说似乎过于冗长和复杂.实现这一目标的更优雅的方式是什么?
This seems overly verbose and complicated to me. What would be a more elegant way of achieving this?
如果可能,我想避免使用 xml 配置.
If possible, I'd like to avoid using xml configuration.
推荐答案
您可以通过 Environment
获取.例如:
You can get it via the Environment
. E.g.:
${@environment.getProperty('name')}
这篇关于使用 Spring 表达式语言访问属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!