Lombok 作为一款跟Spring boot 搭配使用的框架。今天我们来解析一下,熟知的@Getter 注解。
废话不多说,咱们先通过一个小例子引出@Getter注解。
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter(value = AccessLevel.PUBLIC)
@Getter(value = AccessLevel.PUBLIC)
@ToString
public class TestReqDTO {
/**
* 名字
*/
public String name;
/**
* 年龄
*/
public Integer age;
/**
* 性别
*/
public Integer sex;
}
我们都知道 Getter 注解会在 javac 编译的时候进行节点添加 Getter 方法。
package lombok;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Put on any field to make lombok build a standard getter.
* 实例:
* <p>
* Example:
* <pre>
* private @Getter int foo;
* </pre>
*
* will generate:
*
* <pre>
* public int getFoo() {
* return this.foo;
* }
* </pre>
* <p>
* This annotation can also be applied to a class, in which case it'll be as if all non-static fields that don't already have
* a {@code @Getter} annotation have the annotation.
*/
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
public @interface Getter {
// @Getter 注解作用域:private public protected;默认为 public。
lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC;
// @Getter 的 onMethod 属性
AnyAnnotation[] onMethod() default {};
// @Getter 的懒加载机制
boolean lazy() default false;
// @AnyAnnotation 注解
@Deprecated
@Retention(RetentionPolicy.SOURCE)
@Target({})
@interface AnyAnnotation {}
}
根据源码,@Getter 注解可以设置 注解的作用域,onMethod 方法,懒加载机制,@AnyAnnotation。
onMethod 方法使用实例:
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import javax.inject.Inject;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.validation.constraints.Max;
@AllArgsConstructor(onConstructor=@__(@Inject))
public class OnXExample {
// @Getter(onMethod=@__({@Id, @Column(name="unique-id")})) //JDK7
// @Setter(onParam=@__(@Max(10000))) //JDK7
@Getter(onMethod_={@Id, @Column(name="unique-id")}) //JDK8
@Setter(onParam_=@Max(10000)) //JDK8
private long unid;
}
编译后的javac文件
import javax.inject.Inject;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.validation.constraints.Max;
public class OnXExample {
private long unid;
@Inject
public OnXExample(long unid) {
this.unid = unid;
}
@Id @Column(name="unique-id")
public long getUnid() {
return unid;
}
public void setUnid(@Max(10000) long unid) {
this.unid = unid;
}
}
更加详细的,请浏览官网:官网地址
懒加载机制 这个我暂时还没有法相对应的用法。
通过对官网的理解,@Setter 还有更多的花样。这里提供对应的官网的地址 https://projectlombok.org/features/GetterSetter。