使用说明 :本手册按功能分类整理 Lombok 常用注解,包含完整参数说明 、默认行为 和生成代码示例 ,便于开发时快速查阅。
1. 基础 POJO、DTO、VO 注解
@Getter / @Setter
注解位置
类级别:作用于所有非静态字段 字段级别:作用于单个字段
参数说明参数 类型 默认值 说明 valueAccessLevelPUBLIC生成方法的访问级别 onMethod_Annotation[]{}为生成的方法添加注解(Java 8+ 语法) onParam_Annotation[]{}为 setter 参数添加注解
💡 AccessLevel 可选值 :PUBLIC、PROTECTED、PACKAGE、PRIVATE、NONE
使用示例
@Getter
@Setter
public class User { private String name; private int age;
}
public class SecureUser { @Getter ( AccessLevel . PROTECTED) @Setter ( AccessLevel . PRIVATE) private String password; @Getter @Setter private String username;
}
生成代码
public String getName ( ) { return this . name; }
public void setName ( String name) { this . name = name; }
public int getAge ( ) { return this . age; }
public void setAge ( int age) { this . age = age; }
protected String getPassword ( ) { return this . password; }
private void setPassword ( String password) { this . password = password; }
public String getUsername ( ) { return this . username; }
public void setUsername ( String username) { this . username = username; }
@ToString
参数说明参数 类型 默认值 说明 includeFieldNamesbooleantrue是否包含字段名 excludeString[]{}排除的字段名 ofString[]{}仅包含的字段(优先级高于 exclude) callSuperbooleanfalse是否调用父类 toString() doNotUseGettersbooleanfalse直接访问字段而非 getter
使用示例
@ToString ( exclude = { "password" , "secretKey" } )
public class User { private String username; private String password; private String secretKey; private int loginCount;
} @ToString ( of = { "id" , "name" } , callSuper = true )
public class Employee extends Person { private Long id; private String name; private Double salary;
}
生成代码
@Override
public String toString ( ) { return "User(username=" + this . username + ", loginCount=" + this . loginCount + ")" ;
}
@Override
public String toString ( ) { return super . toString ( ) + "Employee(id=" + this . id + ", name=" + this . name + ")" ;
}
@EqualsAndHashCode
参数说明参数 类型 默认值 说明 excludeString[]{}排除的字段 ofString[]{}仅包含的字段 callSuperbooleanfalse是否包含父类字段 doNotUseGettersbooleanfalse直接访问字段 cacheStrategyCacheStrategyCACHE_NOTHING缓存策略(高级用法)
使用示例
@EqualsAndHashCode ( exclude = { "lastModified" } )
public class Article { private Long id; private String title; private LocalDateTime lastModified;
} @EqualsAndHashCode ( callSuper = true )
public class Dog extends Animal { private String breed;
}
生成代码
@Override
public boolean equals ( Object o) { if ( o == this ) return true ; if ( ! ( o instanceof Article ) ) return false ; Article other = ( Article ) o; if ( ! other. canEqual ( this ) ) return false ; final Object this $id = this . id; final Object other$id = other. id; if ( this $id == null ? other$id != null : ! this $id. equals ( other$id) ) return false ; final Object this $title = this . title; final Object other$title = other. title; if ( this $title == null ? other$title != null : ! this $title. equals ( other$title) ) return false ; return true ;
} @Override
public int hashCode ( ) { final int PRIME = 59 ; int result = 1 ; result = result * PRIME + ( this . id == null ? 43 : this . id. hashCode ( ) ) ; result = result * PRIME + ( this . title == null ? 43 : this . title. hashCode ( ) ) ; return result;
}
protected boolean canEqual ( Object other) { return other instanceof Article ;
}
2. 组合注解
@Data
等价注解组合
@Getter
@Setter
@ToString
@EqualsAndHashCode
@RequiredArgsConstructor
注意事项
不生成无参构造器 !需要额外添加 @NoArgsConstructor所有字段都参与 equals/hashCode/toString
使用示例
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product { private Long id; private String name; private Double price;
}
生成代码
包含上述所有注解的生成内容,外加:
public Product ( ) { }
public Product ( Long id, String name, Double price) { this . id = id; this . name = name; this . price = price;
}
@Value
特点
创建不可变类 所有字段自动变为 private final 只生成 getter,不生成 setter 生成全参构造器
使用示例
@Value
public class Point { int x; int y;
}
生成代码
public final class Point { private final int x; private final int y; public Point ( int x, int y) { this . x = x; this . y = y; } public int getX ( ) { return this . x; } public int getY ( ) { return this . y; }
}
3. 构造器注解
@NoArgsConstructor
参数说明参数 类型 默认值 说明 accessAccessLevelPUBLIC构造器访问级别 forcebooleanfalse强制生成(即使有 final 字段)
使用示例
@NoArgsConstructor
public class User { private String name;
} @NoArgsConstructor ( force = true )
public class ImmutableUser { private final String id = "default" ; private final String name;
}
生成代码
public User ( ) { }
public ImmutableUser ( ) { this . name = null ;
}
@AllArgsConstructor
参数说明参数 类型 默认值 说明 accessAccessLevelPUBLIC构造器访问级别 staticNameString""生成静态工厂方法
使用示例
@AllArgsConstructor ( staticName = "of" )
public class Coordinate { private int x; private int y;
}
生成代码
public Coordinate ( int x, int y) { this . x = x; this . y = y;
}
public static Coordinate of ( int x, int y) { return new Coordinate ( x, y) ;
}
@RequiredArgsConstructor
生成规则
为以下字段生成构造器:
所有 final 字段 所有标记 @NonNull 的字段
使用示例
@RequiredArgsConstructor
public class UserService { private final UserRepository userRepository; @NonNull private String defaultRole;
}
生成代码
public UserService ( UserRepository userRepository, String defaultRole) { this . userRepository = userRepository; if ( defaultRole == null ) { throw new NullPointerException ( "defaultRole is marked non-null but is null" ) ; } this . defaultRole = defaultRole;
}
4. Builder 模式注解
@Builder
参数说明参数 类型 默认值 说明 builderMethodNameString"builder"Builder 方法名 buildMethodNameString"build"build 方法名 toBuilderbooleanfalse生成 toBuilder 方法
使用示例
@Builder ( builderMethodName = "newBuilder" , buildMethodName = "create" )
public class Order { private String orderId; private Double amount;
}
生成代码
public static class OrderBuilder { private String orderId; private Double amount; OrderBuilder ( ) { } public OrderBuilder orderId ( String orderId) { this . orderId = orderId; return this ; } public OrderBuilder amount ( Double amount) { this . amount = amount; return this ; } public Order create ( ) { return new Order ( orderId, amount) ; }
}
public static OrderBuilder newBuilder ( ) { return new OrderBuilder ( ) ;
}
@Singular(集合字段支持)
支持的集合类型
List<T> → element(T) 和 elements(Collection<T>)Set<T> → element(T) 和 elements(Collection<T>)Map<K,V> → entry(K, V) 和 entries(Map<K,V>)
使用示例
@Builder
public class ShoppingCart { @Singular ( "product" ) private List < String > products; @Singular private Map < String , Integer > quantities;
}
使用方式
ShoppingCart cart = ShoppingCart . builder ( ) . product ( "Laptop" ) . product ( "Mouse" ) . products ( Arrays . asList ( "Keyboard" , "Monitor" ) ) . entry ( "Laptop" , 1 ) . entries ( Map . of ( "Mouse" , 2 , "Keyboard" , 1 ) ) . build ( ) ;
5. 日志注解
@Slf4j
生成代码
@Slf4j
public class MyService { public void doSomething ( ) { log. info ( "Doing something" ) ; }
}
public class MyService { private static final org. slf4j. Logger log = org. slf4j. LoggerFactory. getLogger ( MyService . class ) ; public void doSomething ( ) { log. info ( "Doing something" ) ; }
}
其他日志框架支持注解 生成的日志实例类型 @Logjava.util.logging.Logger@Log4jorg.apache.log4j.Logger@Log4j2org.apache.logging.log4j.Logger@CommonsLogorg.apache.commons.logging.Log@JBossLogorg.jboss.logging.Logger
6. 高级功能注解
@SneakyThrows
参数说明参数 类型 默认值 说明 valueClass<? extends Throwable>[]Exception.class要 sneaky 抛出的异常类型
使用示例
@SneakyThrows
public String readFile ( String path) { return Files . readString ( Paths . get ( path) ) ;
} @SneakyThrows ( { IOException . class , SQLException . class } )
public void doDatabaseOperation ( ) {
}
生成代码
public String readFile ( String path) { try { return Files . readString ( Paths . get ( path) ) ; } catch ( IOException e) { throw lombok. Lombok. sneakyThrow ( e) ; }
}
@Cleanup
参数说明参数 类型 默认值 说明 valueString"close"清理方法名
使用示例
public byte [ ] readFile ( String path) throws IOException { @Cleanup FileInputStream fis = new FileInputStream ( path) ; return fis. readAllBytes ( ) ;
} public void customResource ( ) { @Cleanup ( "destroy" ) MyResource resource = new MyResource ( ) ;
}
生成代码
public byte [ ] readFile ( String path) throws IOException { FileInputStream fis = new FileInputStream ( path) ; try { return fis. readAllBytes ( ) ; } finally { if ( fis != null ) { fis. close ( ) ; } }
}
@With
使用示例
@With
public class Point { private final int x; private final int y;
}
生成代码
public Point withX ( int x) { return this . x == x ? this : new Point ( x, this . y) ;
} public Point withY ( int y) { return this . y == y ? this : new Point ( this . x, y) ;
}
7. 快速参考表注解 主要用途 关键参数 注意事项 @Getter/@Setter生成访问器 value(AccessLevel)可控制访问级别 @ToString生成 toString exclude, of, callSuper敏感字段务必排除 @EqualsAndHashCode生成相等性方法 exclude, of, callSuper继承时设 callSuper=true @DataPOJO 万能注解 无 不生成无参构造器 @Value不可变对象 无 字段自动 final @NoArgsConstructor无参构造器 forceJPA/JSON 必需 @AllArgsConstructor全参构造器 staticName可生成静态工厂 @RequiredArgsConstructor必需字段构造器 无 Spring 构造器注入推荐 @BuilderBuilder 模式 builderMethodName, toBuilder复杂对象创建首选 @Singular集合 Builder 支持 无 配合 @Builder 使用 @Slf4j日志实例 无 推荐 SLF4J @SneakyThrows绕过检查异常 value谨慎使用 @Cleanup自动资源管理 value(方法名)替代 try-with-resources @With不可变副本 无 函数式编程友好
8. 使用建议
✅ 推荐组合
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString ( exclude = "password" )
public class UserDTO {
}
@Value
@Builder
public class DatabaseConfig {
}
❌ 避免组合
@Data
@Entity
public class User { }
@Data
@Getter
@Setter
public class Product { }
💡 记住 :Lombok 是工具,理解生成的代码才能用好它!