【发布时间】:2018-07-08 05:37:39
【问题描述】:
如果 bean 类来自外部库(例如我自己的公共库),我如何使用 @ConfigurationProperties 填充该 bean?
示例:来自公共库:
package com.my.commons.person;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
@Validated
public class CommonPerson {
private @NotNull String name;
private @NotNull String age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAge() { return age; }
public void setAge(String age) { this.age = age; }
}
实施项目:
package com.my.api;
@SpringBootApplication
public class MainApp extends SpringBootServletInitializer {
@Bean
@ConfigurationProperties("commons.person")
public CommonPerson person() {
return new CommonPerson();
}
}
application.properties(也只在实现项目中):
commons.person.name=Dummy
commons.person.age=30
结果:
由于验证异常,应用程序启动失败。 o.s.b.b.PropertiesConfigurationFactory:对象中的字段错误 字段“名称”上的“commons.person”:拒绝值 [null]...
顺便说一句:如果我将CommonPerson 直接移动到实现项目中,代码将按预期工作。只有当课程来自外部时,它才不起作用......
根据文档,这应该可以工作: @ConfigurationProperties on thirdparty classes
我正在使用 maven 加载我的 commons 包:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>com.my.commons</groupId>
<artifactId>person-commons</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
【问题讨论】:
-
你有这些字段的设置者吗?
-
将 getter 和 setter 添加到您的
CommonPerson类 -
@davidxxx 该死! :D 别再快了! ;)
-
@Yannic Klem heyhey :) 这是一个库类。他/她做不到。
-
不,现在很好。但一切似乎都很好。该错误可能是由您的代码/配置中的某些内容引起的可怕副作用。我建议您要么隔离问题以了解根源,要么使用调试器逐步调试 Spring 处理。
标签: java spring spring-boot