【问题标题】:spring boot binding app properties for nested class嵌套类的spring boot绑定应用程序属性
【发布时间】:2022-10-14 14:32:55
【问题描述】:

我正在尝试使用嵌套属性将应用程序属性绑定到下面的类,但它不起作用,因为我获得了嵌套属性的 NPE。基本上这两个嵌套类共享相同的道具,因此想将其提取到自己的类中。

我想访问像helloPropsInstance.foo.getA() 这样的道具,这可能吗?我也在使用龙目岛。

@ConfigurationProperties(prefix="hello")
@ConstructorBinding
@Getter
@Setter
public class HelloProps {
    Foo foo;
    Bar bar;

    public static class Foo extends Base {}

    public static class Bar extends Base {}

    public static class Base {
        private String a; // works fine if I copy these props to Foo and Bar
        private String b;
        ...
    }

}

【问题讨论】:

  • 删除 static 修饰符。
  • 不要删除static,但请告诉我们您从哪里获得 NPE(foofoo.a),并请确认您有 getter/setterBase(您只在顶级课程上展示了它们)。
  • @chrylis-cautiouslyoptimistic- npe 在 foo 上。我在 Base 上有 getter 和 setter
  • 如果不添加任何新属性,是否有理由不简单地说Base foo = new Base()
  • 目标是为每个班级添加一些额外的道具

标签: java spring-boot lombok


【解决方案1】:

通常,当我们加载属性时,除非重新启动应用程序,否则它们会被视为CONSTANT。在这种情况下,属性可以被视为public final 变量而不需要getterssetters,并通过构造函数进行初始化。 在您的情况下,如果属性是 hello.foo.ahello.bar.a 等,那么您可以执行以下操作:

@ConfigurationProperties(prefix="hello")
@ConstructorBinding
public class HelloProps {
    public final Base foo;
    public final Base bar;

    public HelloProps(Base foo, Base bar) {
        this.foo=foo;
        this.bar=bar;
    }

    @ConstructorBinding    
    public static class Base {
        public final String a; 
        public final String b;

        public Base(String a, String b) {
            this.a=a;
            this.b=b;
        }     
    }
}

有了这个,您所有的属性都可以通过自动装配以helloProps.foo.a helloProps.foo.b 访问,并且您必须已经使用了@ConfigurationPropertiesScan
这只是 Vanilla Java 代码,但对于 Lombok,您可以使用 RequiredArgsConstructor。虽然没有测试。 另外,由于您没有提到FooBar 的任何其他属性,所以我只使用了Base 类。但我不认为,扩展它会是任何问题,因为变量是公共最终的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-10
    • 2015-04-03
    • 2020-06-14
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    相关资源
    最近更新 更多