问题
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.
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;
}
}
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?
If possible, I'd like to avoid using xml configuration.
回答1:
You can get it via the Environment
. E.g.:
${@environment.getProperty('name')}
回答2:
It's very simple to do this in JavaConfig. Here's an example:
@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:
<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.
来源:https://stackoverflow.com/questions/26610030/accessing-properties-file-in-spring-expression-language