Spring配置属性递归类型

时间:2018-10-20 14:09:20

标签: 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"

以及以下配置属性类:

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

该对象将打印EnginealConfig{x=Test{value='Test1', test=null}}。不幸的是,递归无法正常工作。

弄乱尝试各种方法使它起作用后,我尝试将EnginealConfig#Test.test与getter和setter一起从private Test test;更改为private List<Test> test;。然后,通过将列表与一个元素一起使用,此递归将起作用。

以下具有List<Test>更改的application.properties:

engineal.x.value: "Test1"
engineal.x.test[0].value: "Test2"
engineal.x.test[0].test[0].value: "Test3"

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

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

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

2 个答案:

答案 0 :(得分:1)

只需将您的内部类设置为单个类,然后一切都会很好。

application.yml

simple:
  value: aa
  myTest:
    value: lower

配置类

@ConfigurationProperties(prefix = "simple")
@Data //It is for getter setter
public class SimpleConfig {

    private String value;

    private MyTest myTest;
}

递归类

@Data
public class MyTest {
    private String value;
    private MyTest myTest;
}

测试用例

@Resource
private SimpleConfig simpleConfig;

@Test
public void myTest(){

    String value = simpleConfig.getValue();
    System.out.println("outerValue : " + value);
    String innerValue = simpleConfig.getMyTest().getValue();
    System.out.println("innerValue :" + innerValue);
}

结果

outerValue : aa
innerValue :lower

答案 1 :(得分:0)

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

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

        @NestedConfigurationProperty
        private Test test;

您可以使用@NestedConfigurationProperty注释对字段进行注释。

相关问题