Accessing properties file in Spring Expression Language

為{幸葍}努か 提交于 2021-02-07 13:21:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!