Shishigami
Shishigami

Reputation: 451

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.

Upvotes: 6

Views: 13387

Answers (2)

Christopher Schneider
Christopher Schneider

Reputation: 3915

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.

Upvotes: 2

cfrick
cfrick

Reputation: 37008

You can get it via the Environment. E.g.:

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

Upvotes: 28

Related Questions