如何在外部类上加载@ConfigurationProperties?

mem*_*und 6 java spring spring-boot

如果一个bean类来自外部库(例如我自己的commons库),我如何使用填充该bean @ConfigurationProperties

示例:来自公共图书馆:

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

实施项目:

package com.my.api;

@SpringBootApplication
public class MainApp extends SpringBootServletInitializer {
    @Bean
    @ConfigurationProperties("commons.person")
    public CommonPerson person() {
        return new CommonPerson();
    }
}
Run Code Online (Sandbox Code Playgroud)

application.properties(也仅在实施项目中):

commons.person.name=Dummy
commons.person.age=30
Run Code Online (Sandbox Code Playgroud)

结果:

由于验证异常,应用程序启动失败。osbbPropertiesConfigurationFactory:字段“name”上的对象“commons.person”中的字段错误:拒绝值[null]...

顺便说一句:如果我CommonPerson直接将其移至实施项目中,代码将按预期工作。只有当课程来自外部时它才不起作用......

根据文档,这应该可以工作: @ConfigurationProperties onthirdpartyclasses

我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

mem*_*und 0

正如@davidxxx 和其他人所指出的,代码本身是正确的。

在我的例子中,问题可能是 IDE 的一些缓存问题。我刚刚把里面的commons库拿出来pom.xml,保存下来,然后阅读。这以某种方式触发了 IDE 内部的清理,而 amvn clean install没有这样做(因为我之前多次运行过这些 Maven 目标)。