配置
Lombok 的配置非常简单。Lombok 提供了 Maven 和 Gradle 的依赖项,你可以根据需要选择使用。
(1) Maven:
在你的pom.xml中添加以下依赖:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
<scope>provided</scope>
</dependency>
(2) Gradle:
在你的build.gradle中添加以下依赖:
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.34'
annotationProcessor 'org.projectlombok:lombok:1.18.34'
}
@Builder
建造者模式是开发中非常常见的设计模式。它允许我们逐步构建对象,并对其配置进行细粒度控制,同时保持构造代码的简洁。
在没有 Lombok 的情况下,代码通常如下所示:
public class Order {
privatefinal String customerName;
privatefinal Address deliveryAddress;
private Order(String customerName, Address deliveryAddress) {
this.customerName = customerName;
this.deliveryAddress = deliveryAddress;
}
public static OrderBuilder builder() {
returnnew OrderBuilder();
}
publicstaticclass OrderBuilder {
private String customerName;
private Address deliveryAddress;
OrderBuilder(){};
public Builder customerName(String name) {
this.customerName = name;
returnthis;
}
public Builder deliveryAddress(Address address) {
this.deliveryAddress = address;
returnthis;
}
public Order build() {
returnnew Order(customerName, deliveryAddress);
}
}
}
使用 Lombok 的实现:
@Builder
public class Order {
private final String customerName;
private final Address deliveryAddress;
}
这是一个非常简单的例子,但实际上还有很多其他注解可以定制建造者设计模式。我将在下一篇文章中介绍它们。
@Data
这个注解将一些常见的 Lombok 注解结合在一起:
- @ToString
- @Getter
- @Setter
- @EqualsAndHashCode
- @RequiredArgsConstructor
没有 Lombok 的示例:
public class UserInfo {
private String username;
private String password;
private String email;
public UserInfo(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
// 一些实现
}
@Override
public int hashCode() {
return Objects.hash(username, password, email);
}
@Override
public String toString() {
return"UserInfo(" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
')';
}
}
使用 Lombok 的实现:
@Data
public class UserInfo {
private String username;
private String password;
private String email;
}
@Value
如果我们希望所有字段默认都是私有的且不可变的(没有 setter 方法),可以使用@Value 注解,如下所示:
@Value
public class UserInfo {
private String username;
private String password;
private String email;
}
@NonNull
这个注解用于为任何方法或构造函数参数生成空值检查语句。
public void setEmail(@NonNull String email) {
this.email = email;
}