java 使用 Spring 表达式语言访问属性文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26610030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing properties file in Spring Expression Language
提问by Shishigami
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.
我使用 Spring Boot 使用 Thymeleaf 创建了一个简单的 Web 应用程序。我使用 application.properties 文件作为配置。我想要做的是向该文件添加新属性,例如名称和版本,并从 Thymeleaf 访问值。
I have been able to achieve this by creating a new JavaConfiguration class and exposing a Spring Bean:
我已经能够通过创建一个新的 JavaConfiguration 类并公开一个 Spring Bean 来实现这一点:
@Configuration
public class ApplicationConfiguration {
@Value("${name}")
private String name;
@Bean
public String name() {
return name;
}
}
I can then display it in a template using Thymeleaf like so:
然后我可以使用 Thymeleaf 在模板中显示它,如下所示:
<span th:text="${@name}"></span>
This seems overly verbose and complicated to me. What would be a more elegant way of achieving this?
这对我来说似乎过于冗长和复杂。实现这一目标的更优雅的方式是什么?
If possible, I'd like to avoid using xml configuration.
如果可能,我想避免使用 xml 配置。
回答by cfrick
You can get it via the Environment
. E.g.:
您可以通过Environment
. 例如:
${@environment.getProperty('name')}
回答by Christopher Schneider
It's very simple to do this in JavaConfig. Here's an example:
在 JavaConfig 中执行此操作非常简单。下面是一个例子:
@Configuration
@PropertySource("classpath:my.properties")
public class JavaConfigClass{
@Value("${propertyName}")
String name;
@Bean //This is required to be able to access the property file parameters
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
}
Alternatively, this is the XML equivalent:
或者,这是等效的 XML:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>my.properties</value>
</property>
</bean>
Finally, you can use the Environment variable, but it's a lot of extra code for no reason.
最后,您可以使用环境变量,但它无缘无故地增加了很多额外的代码。