【问题标题】:@Value can reads, but @ConfigurationProperties can't@Value 可以读取,但 @ConfigurationProperties 不能
【发布时间】:2017-12-29 13:07:34
【问题描述】:

我正在尝试读取这样的 yml 文件。

order:
  foo: 5000
  bar: 12

我可以用@value 阅读它。 (顺便说一句,我正在使用 Lombok)

@Component
@Data
public class WebConfigProperty {

    private Integer foo;
    private Integer bar;

    public WebConfigProperty(@Value("${order.foo}") @NonNull final Integer foo,
            @Value("${order.bar}") @NonNull final Integer bar) {
        super();
        this.foo = foo;
        this.bar = bar;
    }
}

我正在尝试使用@ConfigurationProperties,因为 yml 文件会更加复杂。但它不适用于@ConfigurationProperties

@Component
@ConfigurationProperties("order")
@Data
public class WebConfigProperty {

    @NonNull
    private Integer foo;
    @NonNull
    private Integer bar;
}

我还在配置类中添加了@EnableConfigurationProperties。 config中的所有注解都是这样的。

@SpringBootConfiguration
@EnableConfigurationProperties
@EnableAutoConfiguration(exclude = { ... })
@ComponentScan(basePackages = { ... })
@Import({ ... })
@EnableCaching

错误信息是这样的。

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in {...}.WebConfigProperty required a bean of type 'java.lang.Integer' that could not be found.


Action:

Consider defining a bean of type 'java.lang.Integer' in your configuration.

似乎 Spring 找不到 yml 文件并试图将空值放入 WebConfigProperty 字段中。我不知道为什么。

仅供参考,这是一个使用 Gradle 的多项目应用程序。 yml 文件和一个配置类(未写)在同一个项目中。 WebConfigProperty 在另一个项目中。

编辑: 根据@Yannic Klem 的回答,这两个有效。

@Component
@ConfigurationProperties("order")
@Getter
@Setter
@EqualsAndHashCode
public class WebConfigProperty {

    @NonNull
    private Integer foo;
    @NonNull
    private Integer bar;
}

//OR

@Component
@ConfigurationProperties("order")
@Data
@NoArgsConstructor
public class WebConfigProperty {

    @NonNull
    private Integer foo;
    @NonNull
    private Integer bar;
}

【问题讨论】:

  • 我认为问题出在@Data 注释上。我提供了一个答案,但我目前无法验证。告诉我它是否不是@Data 注释
  • 尝试明确地使用@Getter@Setter 而不是@Data
  • 你可以试试@ConfigurationProperties(prefix = "order") 吗?

标签: spring spring-boot annotations yaml javabeans


【解决方案1】:

Lomboks @Data 注解添加了@RequiredArgsConstructor。 然后 Spring 尝试将参数自动装配到构造函数。

这会导致您的异常,因为它尝试查找 Integer 类型的两个 bean:foo 和 bar。

@ConfigurationProperties 应该只有一个默认构造函数和 getter + setter 的属性。 然后这些属性将由这些设置器绑定到您的 @ConfigurationProperties 类。

您的WebConfigProperty 可能如下所示:

@Component
@ConfigurationProperties("order")
/**
* Not sure about IDE support for autocompletion in application.properties but your
* code should work. Maybe just type those getters and setters yourself ;)
*/
@Getters 
@Setters
public class WebConfigProperty {

  @NonNull
  private Integer foo;
  @NonNull
  private Integer bar;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    相关资源
    最近更新 更多