【问题标题】:How to load @ConfigurationProperties on external class?如何在外部类上加载@ConfigurationProperties?
【发布时间】: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


【解决方案1】:

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

我的问题可能是 IDE 的一些缓存问题。我刚刚取出pom.xml 中的commons 库,保存并阅读。这以某种方式触发了 IDE 内部的清理,而 mvn clean install 没有(因为我之前多次运行这些 maven 目标)。

【讨论】:

    【解决方案2】:

    尝试使用...@EnableConfigurationProperties 注解启用配置属性支持,这可能会有所帮助。

    一些例子和用法说明: 12

    【讨论】:

      猜你喜欢
      • 2014-01-22
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多