@Value 可以读取,但 @ConfigurationProperties 不能

use*_*379 0 spring yaml annotations javabeans spring-boot

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

order:
  foo: 5000
  bar: 12
Run Code Online (Sandbox Code Playgroud)

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

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

    @NonNull
    private Integer foo;
    @NonNull
    private Integer bar;
}
Run Code Online (Sandbox Code Playgroud)

我还添加@EnableConfigurationProperties了一个配置类。配置中的所有注释都是这样的。

@SpringBootConfiguration
@EnableConfigurationProperties
@EnableAutoConfiguration(exclude = { ... })
@ComponentScan(basePackages = { ... })
@Import({ ... })
@EnableCaching
Run Code Online (Sandbox Code Playgroud)

错误信息是这样的。

***************************
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.
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

Yan*_*lem 6

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

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

@ConfigurationProperties属性应该只有一个默认的构造函数和 getters + setters。然后,这些属性将@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;
}
Run Code Online (Sandbox Code Playgroud)