Spring ConfigurationProperties 与流畅的 setter 或自定义 setter 一起使用 [英] Spring ConfigurationProperties to work with fluent setters or custom setters

查看:20
本文介绍了Spring ConfigurationProperties 与流畅的 setter 或自定义 setter 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在将 lombok 项目用于 setter 和 getter,我们更喜欢 setter 和 getter 的流畅访问器吸气剂.当我们将 ConfigurationProperties 与流畅的访问器一起使用时,就会出现问题.Spring 无法将属性与类字段连接起来.当我们删除 Accessor 注释并使用经典的 setter 和 getter 时,同样的事情也会起作用.有没有一种方法可以将自定义 setter 与 Configurationproperties 一起使用

We are using project lombok for setters and getters and we prefer fluent accessors for setter & getters . The problem arises when we use ConfigurationProperties with fluent accessors. Spring is not able to wire the properties with the class fields . The same things works when we remove the Accessor annotation and have the classic setters and getters. Is there a way we can use custom setters with Configurationproperties

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;

}

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

We get a null pointer exception while accessing this property as

properties.property1()

推荐答案

作为 Spring(因此 Spring Boot)使用 Java Beans 规范,为此它使用可用的默认 JDK 支持.

As Spring (and thus Spring Boot) uses the Java Beans Specification and for this it uses the default JDK support available.

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

The introspection and reflection API defines properties as a getter/setter. Setters are void and getters should return the actual field (the return and method argument types must also match).

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

So with that in mind Spring doesn't support custom getters/setters, simply because the JDK classes don't provide this.

这篇关于Spring ConfigurationProperties 与流畅的 setter 或自定义 setter 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆