从thymeleaf访问默认的@ConfigurationProperties属性

时间:2020-11-12 09:01:55

标签: java spring-boot thymeleaf spring-properties

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

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

我正在尝试使用

读取百里香叶中的location属性。
${@environment.getProperty('storage.location')}

但是什么也没显示。

编辑: 如果我在 application.properties 中设置了storage.location=to something else,它将起作用。但是为什么百里香不选择默认值?

2 个答案:

答案 0 :(得分:0)

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

您只需annotate the getter method with @Bean并以您希望该属性命名的方式对其进行命名:

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

如果要命名吸气剂方法getLocation(),也可以通过设置name of the @Bean来做到这一点:

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

如果我在storage.location=to something else中设置了application.properties,它将起作用。但是为什么百里香不选择默认值?

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

如果没有,Spring认为这只是其他事情的吸气剂。

答案 1 :(得分:0)

如果将属性类更改为:

import {useStore} from 'vuex'
setup(){
    const store=useStore()// store instead of `$store`
}

然后您可以在Thymeleaf中这样做:

@Component("fileSystemStorageProperties") // Use @Component instead of @Configuration and give the bean an explicit name
@ConfigurationProperties(prefix = "storage")
public class FileSystemStorageProperties {
    private String location = "image-dir";

    public String getLocation() {
        return location;
    }

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

有关更多信息,请参见https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html#spring-beans

相关问题