【问题标题】:Why default values from @ConfigurationProperties class do not work?为什么 @ConfigurationProperties 类的默认值不起作用?
【发布时间】:2016-07-01 13:05:20
【问题描述】:

我的 Spring Boot 应用程序中有一个 typesafe configuration 的课程:

@Component
@ConfigurationProperties(prefix = "props")
@Getter
@Setter
public class Properties {
    private String param1 = "val1";
    private String param2 = "val2";
}

稍后我尝试在带有注释的 bean 中的字段上使用它:@Value("${props.param1}")

但我在应用程序启动时遇到以下异常,直到我在 application.properties 中为我的自定义属性指定一个值

原因:java.lang.IllegalArgumentException:无法解析 字符串值“${props.param1}”中的占位符“props.param1”

如何使 Spring Boot 应用程序使用默认值而不在 application.properties 中指定值?

当我在application.properties 中键入属性并且生成的spring-configuration-metadata.json 文件中有一个defaultValue 时,我在IDE 中看到了默认值。我想这个默认值应该与 spring 一起使用,直到我在我的属性文件中覆盖它,但由于未知原因,我从上面得到了异常。

【问题讨论】:

  • 您究竟是如何使用Properties 组件的?使用@Value 或@Autowired?
  • @AliDehghani 我提到了,我使用了@Value)
  • @AliDehghani 我尝试设置它而不是在我的主类上设置 - 没有区别

标签: java spring spring-boot


【解决方案1】:

后来我尝试在带有注释的 bean 中的字段上使用它: @Value("${props.param1}")

这种所谓的 Typesafe 配置 是一种使用属性的替代方法,它允许强类型 bean 管理和验证应用程序的配置。

引入ConfigurationProperties 的重点是不要使用繁琐且容易出错的@Values。而不是使用@Value,您应该使用@Autowired 来注入Properties 配置:

@Service // or any other Spring managed bean
public class SomeService {
    /**
     * After injecting the properties, you can use properties.getParam1()
     * to get the param1 value, which is defaults to val1
     */
    @Autowired private Properties properties; 

    // Other stuff
}

如果您坚持使用@Value,请先删除Properties 类,然后使用@Value("${key:defaultValue}") 表示法,如下所示:

@Value("${props.param1:val1}")

【讨论】:

  • 看起来我对类型安全属性有错误的想象。感谢您的解释。我应该在哪里使用配置类的吸气剂?根据文档,我可以使用@PostConstruct 方法。
  • 如果你指的是getParam1、getParam2等,你可以在任何Spring托管bean中使用它们(@Repository、@Component、@Service、@Configuration)。 Spring Boot 本身就大量使用了这些配置属性,比如你可以看看github.com/spring-projects/spring-boot/blob/master/…
  • 我在该链接上看到了@EnableConfigurationProperties 注释,但不明白它是如何使用的
  • 显然不需要使用@EnableConfigurationProperties。见这里stackoverflow.com/questions/38146207/…
猜你喜欢
  • 1970-01-01
  • 2018-08-12
  • 2020-10-31
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 2016-11-24
  • 2020-06-13
相关资源
最近更新 更多