如果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>