Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 227
Shishigami Avatar asked Oct 28 '14 13:10

Shishigami


People also ask

How do you access properties in spring boot?

Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.

Which annotation uses SpEL expression language to access the property values DOT property file?

SpEL expressions may also be used to define beans using annotation-based configuration metadata. To define a default value, use the @Value annotation on fields, methods, and method/constructor arguments.

How load properties file in spring application?

We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name. For example, if we define a “staging” environment, that means we'll have to define a staging profile and then application-staging. properties.


1 Answers

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

${@environment.getProperty('name')}
like image 132
cfrick Avatar answered Nov 02 '22 23:11

cfrick