【问题标题】:Spring ConfigurationProperties to work with fluent setters or custom settersSpring ConfigurationProperties 与流利的设置器或自定义设置器一起使用
【发布时间】:2019-12-10 00:50:43
【问题描述】:

我们将项目 lombok 用于 setter 和 getter,我们更喜欢 fluent 访问器用于 setter 和 getter。当我们将 ConfigurationProperties 与流畅的访问器一起使用时,就会出现问题。 Spring 无法将属性与类字段联系起来。当我们删除 Accessor 注释并拥有经典的 setter 和 getter 时,同样的事情会起作用。有没有办法我们可以使用带有配置属性的自定义设置器

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties
@Data
@Accessors(fluent = true)
public class Properties {

     private String property1;

     private String property2;

}

我们在访问这个属性时得到一个空指针异常

properties.property1()

【问题讨论】:

  • Spring 使用 Java Bean 规范来识别属性。这些都是硬连线到 JDK 支持类(自省和反射)中的。所以目前 spring (boot) 不支持自定义 getter 和 setter。

标签: java spring spring-boot


【解决方案1】:

由于 Spring(以及 Spring Boot)使用 Java Beans Specification,因此它使用可用的默认 JDK 支持。

自省和反射 API 将属性定义为 getter/setter。 setter 是void,getter 应该返回实际的字段(返回和方法参数类型也必须匹配)。

因此考虑到这一点,Spring 不支持自定义 getter/setter,仅仅是因为 JDK 类不提供此功能。

【讨论】:

    【解决方案2】:

    该框架使用约定命名为 get***/is*** 用于 getter,set*** 用于 setter。 此外,@Accessors lombok 功能仍是实验性。请看这个link

    【讨论】:

    • 好的。谢谢。这是否意味着 spring 很难使用像 public void set(Foo foo){...} 这样的传统设置器,对吗?
    猜你喜欢
    • 2012-05-25
    • 1970-01-01
    • 2011-09-22
    • 2013-01-25
    • 2018-07-27
    • 1970-01-01
    • 2017-07-16
    • 2017-03-01
    • 1970-01-01
    相关资源
    最近更新 更多