【发布时间】: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