无法使用@ConfigurationProperties获取特定属性

时间:2015-09-11 11:56:55

标签: spring-boot

我想检索一个属性但是当使用一个点时,我不能,我得到null, 有没有办法继续使用@ConfigurationProperties?

参见示例:

@Component
@ConfigurationProperties(prefix = "prop.foo")
public class Test {
    //This is working
    private String myVal;
    //This is not working
    private String barAnotherVal;

    public void setMyVal(String myVal) {
        this.myVal= myVal;
    }
    public void setBarAnotherVal(String barAnotherVal) {
        this.barAnotherVal= barAnotherVal;
    }
}

application.properties:

prop.foo.myVal
prop.foo.bar.anotherVal

1 个答案:

答案 0 :(得分:2)

要在barAnotherVal设置Test,您的媒体资源必须为prop.foo.barAnotherValue

如果您想使用prop.foo.bar.anotherValue,那么bar上需要Test的媒体资源。然后,bar类型应具有anotherValue属性。像这样:

@Component
@ConfigurationProperties(prefix = "prop.foo")
public class Test {

    private String myVal;

    private Bar bar = new Bar();

    public void setMyVal(String myVal) {
        this.myVal = myVal;

    public Bar getBar() {
        return this.bar;
    }

    public static class Bar {

        private String anotherVal;

        public void setAnotherVal(String anotherVal) {
            this.anotherVal = anotherVal;
        }
    }
}