简体   繁体   中英

Accessing properties file in Spring Expression Language

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.

You can get it via the Environment . Eg:

${@environment.getProperty('name')}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM