首页 > 解决方案 > 从 thymeleaf 访问默认的 @ConfigurationProperties 属性

问题描述

我正在尝试使用 thymeleaf 读取属性,但无法使其正常工作。我有以下属性类:

@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;
    }
}

我正在尝试使用 thymeleaf 读取 location 属性

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

但是什么都没有显示。

编辑:如果我storage.location=to something elseapplication.properties中设置,它可以工作。但是为什么 thymeleaf 不选择默认值呢?

标签: javaspring-bootthymeleafspring-properties

解决方案


Spring 不会根据变量名自动加载参数。

您可以只使用注释 getter 方法@Bean并按照您希望属性命名的方式对其进行命名:

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

如果你想命名你的getter方法getLocation(),你也可以通过设置名称@Bean来做到这一点:

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

如果我设置storage.location=to something elseapplication.properties它的工作原理。但是为什么 thymeleaf 不选择默认值呢?

如果您在 中设置值application.propererties,spring 会将其识别为属性并使用它。

如果不是,spring 认为它只是其他东西的吸气剂。


推荐阅读