Search code examples
javaspring-bootthymeleafspring-properties

Acces default @ConfigurationProperties property from thymeleaf


I am trying to read a property using thymeleaf and I can't get it to work. I have the following property class:

@Configuration
@ConfigurationProperties(prefix = "storage")
public class FileSystemStorageProperties {
    private String location = "image-dir";

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

And I am trying to read the location property in thymeleaf using

${@environment.getProperty('storage.location')}

however nothing is displayed.

EDIT: If I set storage.location=to something else in application.properties, it works. But why doesn't thymeleaf pick the default value??


Solution

  • Spring does not automatically load parameters based on the variable name.

    You can just annotate the getter method with @Bean and name it the way you want the property to be named:

    @Bean
    public String location() {
        return location;
    }
    

    If you want to name you getter method getLocation(), you can do that too by setting the name of the @Bean:

    @Bean(name="location")
    public String getLocation() {
        return location;
    }
    

    If I set storage.location=to something else in application.properties, it works. But why doesn't thymeleaf pick the default value??

    If you set the value in the application.propererties, spring recognizes that as property and uses it.

    If not, spring thinks it is just a getter for something else.