Java Spring配置属性文件-提供默认值

Java Spring配置属性文件-提供默认值,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个类似这样的ConfigurationProperties类,可以显示我需要什么 @ConfigurationProperties(prefix = "something") @Configuration @Data public class SomethingProps { private OtherProps otherProps; } 当我在application.yml文件中提供这个时,一切都正常 something: otherProps:

我有一个类似这样的ConfigurationProperties类,可以显示我需要什么

@ConfigurationProperties(prefix = "something")
@Configuration
@Data
public class SomethingProps {

    private OtherProps otherProps;
}
当我在application.yml文件中提供这个时,一切都正常

something:
   otherProps: true 
但是当我在yml文件中根本不提供otherProps时,当在构造函数中自动连接otherProps时,我会得到一个空指针异常。我的期望是它会默认为true,我已经尝试使用@NotNull进行注释

@Configuration
@EnableConfigurationProperties(value = { OtherProps.class })
@Data
public class SomethingProps {


}
然后

@Data
@ConfigurationProperties(prefix = "something")
public class OtherProps {

private boolean enabled = true;
}
初始化其他道具


我通常使用以下方法:

@ConfigurationProperties
public class SomethingProperties {
   private OtherProps otherProps = new OtherProps();
   // getters/setters/lombok generated whatever

   public static class OtherProps {
     private boolean enabled = true;
     // getters/setters/lombok generated whatever
   }
}


@Configuration
@EnableConfigurationProperties(SomethingProps.class) 
public class MyConfiguration {
   @Bean 
   public SampleBean sampleBean(SomethingProps config) {
      return new SampleBean(config.getOtherProps().isEnabled());
   }
}

我建议您导入配置类,而不是创建对象

例如

@ConfigurationProperties(prefix = "something")
@Configuration
@Import({OtherProps.class})
@Data
public class SomethingProps {

}
你的其他道具课是这样的

@Data
public class OtherProps {

    private boolean enabled = true;
}

实际上,您可以使用@Value注释作为替代方法

@Value("x.y.z:default_value")
private boolean isEnabled;

您还需要创建OtherProps的实例,您需要初始化OtherProps字段。在Spring Boot自己的属性类中也是这样做的。这不起作用,到目前为止唯一有效的解决方案是创建对象,它没有那么整洁,所以我们更喜欢这样,但似乎无法解决问题
@Data
public class OtherProps {

    private boolean enabled = true;
}
@Value("x.y.z:default_value")
private boolean isEnabled;