Spring配置属性递归类型

eng*_*eAL 11 java spring spring-boot

我正在尝试创建一个具有递归类的配置属性类,该类的结构类似于链表。我正在使用Spring boot 2.0.6.RELEASE,并且正在使用来自动连接该类@EnableConfigurationProperties({EnginealConfig.class})

我遇到的问题是,只有第一个级别将被绑定到Test对象,x.test永远不会被设置。

使用以下application.properties文件:

engineal.x.value: "Test1"
engineal.x.test.value: "Test2"
engineal.x.test.test.value: "Test3"
Run Code Online (Sandbox Code Playgroud)

以及以下配置属性类:

@ConfigurationProperties(prefix = "engineal")
public class EnginealConfig {

    static class Test {

        private String value;
        private Test test;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public Test getTest() {
            return test;
        }

        public void setTest(Test test) {
            this.test = test;
        }

        @Override
        public String toString() {
            return "Test{" +
                    "value='" + value + '\'' +
                    ", test=" + test +
                    '}';
        }
    }

    private Test x;

    public Test getX() {
        return x;
    }

    public void setX(Test x) {
        this.x = x;
    }

    @Override
    public String toString() {
        return "EnginealConfig{" +
                "x=" + x +
                '}';
    }
}
Run Code Online (Sandbox Code Playgroud)

该对象将打印EnginealConfig{x=Test{value='Test1', test=null}}。不幸的是递归不起作用。

在尝试了各种不同的方法以使其正常工作之后,我尝试将EnginealConfig#Test.test 与getter和setter一起从更改private Test test;private List<Test> test;。然后,通过将列表与一个元素一起使用,此递归将起作用。

以下application.properties进行了List<Test>更改:

engineal.x.value: "Test1"
engineal.x.test[0].value: "Test2"
engineal.x.test[0].test[0].value: "Test3"
Run Code Online (Sandbox Code Playgroud)

将输出EnginealConfig{x=Test{value='Test1', test=[Test{value='Test2', test=[Test{value='Test3', test=null}]}]}}。然后,我可以使用来访问下一个元素test.get(0)

因此,似乎仅当递归类型在集合中时才支持递归。

虽然可以采用这种解决方法,但我更喜欢使用第一种方法。是否/应该在不需要集合的情况下支持递归类?谢谢您的帮助!

Dar*_*ght 0

@ConfigurationProperties(prefix = "engineal")
public class EnginealConfig {

    static class Test {
        //@NestedConfigurationProperty
        private String value;

        @NestedConfigurationProperty
        private Test test;
Run Code Online (Sandbox Code Playgroud)

您可以使用注释来注释该字段@NestedConfigurationProperty

  • 实际上,文档中指出“此注释对实际绑定过程没有影响”:https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties /NestedConfigurationProperty.html (3认同)