代码之家  ›  专栏  ›  技术社区  ›  Roland Weisleder

@ConfigurationProperties的默认值不存在

  •  0
  • Roland Weisleder  · 技术社区  · 7 年前

    在一个Spring Boot应用程序中,我有一个properties对象,它包含验证和默认值。

    @SpringBootApplication
    public class DummyApplication {
    
        @Validated
        @ConfigurationProperties(prefix = "dummy")
        public static class DummyProperties {
    
            @NotNull
            private String prop = "test";
    
            // getter, setter ...
        }
    
        @Component
        @EnableConfigurationProperties(DummyProperties.class)
        public static class DummyComponent {
    
            @Autowired
            public DummyComponent(DummyProperties properties) {
                Assert.notNull(properties.prop, "prop should have a value");
    
                // ...
            }
        }
    
        public static void main(String[] args) {
            SpringApplication.run(DummyApplication.class, args);
        }
    }
    

    这适用于1.4.x版的弹簧靴。

    对于SpringBoot1.5.x和2.0.x,我得到一个异常,因为 properties.prop 为空。但它不应该为空,因为我在上面定义了一个默认值,并且没有在代码之外设置其他值。

    @Validated 注解。

    发生了什么?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Roland Weisleder    7 年前

    解决方案

    替换 properties.prop 具有 properties.getProp()

    注解 @Validated 使Spring用代理对象包装DummyProperties的实例。

    代理对象将所有方法调用委托给基础对象,因此getter和setter按预期工作。但代理对象不委托字段访问,因此使用该代理对象的值。不幸的是,字段值不是从基础对象复制的,因此字段是用null初始化的。