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

问题描述 投票:0回答:1

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

order:
  foo: 5000
  bar: 12

我可以用@value阅读它。 (我正在使用Lombok btw)

@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。配置中的所有注释都是这样的。

@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;
}
spring spring-boot annotations yaml javabeans
1个回答
3
投票

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

这会导致您的异常,因为它尝试查找Integer类型的两个bean: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;
}
© www.soinside.com 2019 - 2024. All rights reserved.