Java 用Spring表达式语言访问属性文件
我使用SpringBoot创建了一个简单的web应用程序。我使用application.properties文件作为配置。我想做的是向该文件添加新属性,如名称和版本,并从Thymeleaf访问值 我通过创建一个新的JavaConfiguration类并公开一个Springbean实现了这一点:Java 用Spring表达式语言访问属性文件,java,spring,spring-boot,thymeleaf,Java,Spring,Spring Boot,Thymeleaf,我使用SpringBoot创建了一个简单的web应用程序。我使用application.properties文件作为配置。我想做的是向该文件添加新属性,如名称和版本,并从Thymeleaf访问值 我通过创建一个新的JavaConfiguration类并公开一个Springbean实现了这一点: @Configuration public class ApplicationConfiguration { @Value("${name}") private String name;
@Configuration
public class ApplicationConfiguration {
@Value("${name}")
private String name;
@Bean
public String name() {
return name;
}
}
然后,我可以使用Thymeleaf将其显示在模板中,如下所示:
<span th:text="${@name}"></span>
这对我来说似乎过于冗长和复杂。实现这一目标的更优雅的方式是什么
如果可能,我希望避免使用xml配置。您可以通过
环境获得它。例如:
${@environment.getProperty('name')}
在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();
}
}
或者,这是XML等价物:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>my.properties</value>
</property>
</bean>
我的财产
最后,您可以使用环境变量,但这是一个没有任何原因的大量额外代码。这不是与“${name}”相同吗?@DaveSyer不,这在th:text=“${name}”
中对我不起作用,谢谢,这正是我想要的。我最初尝试使用${name},但也无法实现。你知道为什么它在@Value中起作用吗?在@Value
中,它应该一直起作用——这就是关键所在。我猜“${}”占位符在Thymeleaf中的含义有所不同(它们应该是模型属性)。