About @Accessors of Lombok

@Accessors: Annotations for customizing getters/setters Use with @ Getter/@ Setter etc. There are three options: "chain", "fluent", and "prefix".

environment

Java : 1.8 Lombok : 1.18.16 (SpringBoot : 2.3.7)

method chaining of setter

Make the setter a method chain with @Accessors (chain = true)

user.setName("Tom").setAge(24);

Can be described continuously like

public User setName(final String name) {
	this.name = name;
	return this;
}
It can be attached to either a class or a field, but regardless of which one is attached ** If there is at least one in the class, it will be applied to all fields **

Use getter/setter in field name

@Accessors(fluent = true) Allow getter/setter names to be used in field names ↓

String name = user.name();  // getter
user.name("Tom");           // setter

Getter/setter can be described by field name like

public String name() {
	return this.name;
}

public void name(final String name) {
	this.name = name;
	return this;
}
It can be attached to a class or a field, unlike chain, when attached to a field ** Applies only to that field **

Define getter/setter using the name excluding the prefix part

@Accessors(prefix = "f")
private String fName;

Define getter/setter using the name excluding the prefix part in ↓

String name = user.getName();  // getter
user.setName("Tom");           // setter

Getter/setter can be described with the name excluding the prefix part like.

public String getName() {
	return this.fName;
}

public void setName(final String fName) {
	this.fName = fName;
}

Can be attached in class or in the field → When assigned to a class: ** Applies to all fields **, getter/setter is not generated for fields that do not meet the prefix ** When given to a field: ** Applies to that field only **
@Getter
@Setter
@Accessors(prefix = {"f", "t"})
public class User {
	private Integer id;
	private String fName;
	private Integer tAge;
}

↓ ○ Code that is actually generated

public String getName() {
	return this.fName;
}

public void setName(final String fName) {
	this.fName = fName;
}

public Integer getAge() {
	return this.tAge;
}

public void setAge(final String tAge) {
	this.tAge = tAge;
}

Since private Integer id; does not have "f" or "t" described as prefix, no code is generated.

Recommended Posts