Lombok常用注解总结
什么是Lombok
Lombok是一个通过使用注解修饰,来简化Java代码的一个工具库。
官网中为大家展示了如何将 Lombok 作为扩展,添加到 IDE上。
官网地址:https://projectlombok.org/
下面为大家介绍一些常用的Lombok工具注解:
基本注解:
注解 | 功能 |
---|---|
@ToString | 修饰JavaBean,可以动态生成相应的ToString方法, 格式为:User(username=admin, password=123)<br / |
@EqualsAndHashCode | 修饰JavaBean,默认情况下,会使用所有非静态(non-static)和非瞬态(non-transient)属性来生成equals和hasCode |
@Getter | 可以修饰JavaBean,也可以修饰属性,生成相应属性的get()方法 |
@Setter | 可以修饰JavaBean,也可以修饰属性,生成相应属性的set()方法 |
@NonNull | 修饰方法参数,自动判断参数是否为null,为nulll则抛出NullPointerException |
@NoArgsConstructor | 修饰JavaBean,可以动态生成无参构造器方法 |
@RequiredArgsConstructor | 修饰JavaBean,生成private构造方法,使用staticName选项生成指定名称的static方法,与@NonNull联用,指定那些属性是本方法参数 |
@AllArgsConstructor | 修饰JavaBean,可以动态生成全参构造器方法 |
@Data | 修饰JavaBean,集合了@ToString、@EqualsAndHashCode、@Getter/@Setter、@RequiredArgsConstructor的所有特性。 |
@Value | 修饰JavaBean,和@Data类似,区别在于它会把所有成员变量默认定义为private final修饰,并且不会生成set方法 |
@Slf4j | 修饰JavaBean,当项目中使用Slf4j日志架构的时候自动创建log日志实例 |
@Log4j | 修饰JavaBean,当项目中使用Log4j日志架构的时候自动创建log日志实例,需要创建log4j.properties配置文件,推荐使用@Log4j2 |
@Log4j2 | 修饰JavaBean,当项目中使用Log4j日志架构的时候自动创建日志实例,不需要配置文件 |
@Synchronized | 修饰方法,自动生成同步代码块锁 |
@Cleanup | 修饰流变量,自动调用close()方法 |
高级注解:
注解 | 功能 |
---|---|
@Accessors(chain=true) | 修饰JavaBean,链式风格,在调用set方时,返回当前实例 |
@Builder | 修饰JavaBean,构建者模式,不可与@NoArgsConstructor同时使用 |
@Delegate | 修饰JavaBean,代理模式 |
IDEA Lombok 插件安装
打开IDEA
Ctrl + Alt + S 打开 设置面板
在Plugins的Marketplace中搜索Lombok
Lombok Maven坐标
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
Lombok 公共属性
属性 | 作用 |
---|---|
exclude | 不包含哪些属性 示例:@ToString(exclude = {“username”}) |
of | 包含哪些属性 示例:@ToString(of = {“username”}) |
callSuper | 是否包含超类 示例:@ToString(callSuper=true) |
示例参考@ToString
Lombok 基础注解 详解
@ToString
修饰JavaBean,可以动态生成相应的ToString方法,格式为:User(username=admin, password=123)
@ToString(exclude={“column1”,“column2”}):排除多个column列所对应的元素
@ToString(of={“column1”,“column2”}):只生成包含多个column列所对应的元素
代码实现
public class Test {
public static void main(String[] args) {
User1 user1 = new User1().setUsername("admin").setPassword("123");
System.out.println(user1);
User2 user2 = new User2().setUsername("admin").setPassword("123");
System.out.println(user2);
User3 user3 = new User3().setUsername("admin").setPassword("123");
System.out.println(user3);
User4 user4 = new User4().setUsername("admin").setPassword("123");
System.out.println(user4);
}
}
@ToString
class User1{
private String username;
private String password;
public User1 setUsername(String username) {
this.username = username;
return this;
}
public User1 setPassword(String password) {
this.password = password;
return this;
}
}
@ToString(exclude = {"username"})
class User2{
private String username;
private String password;
public User2 setUsername(String username) {
this.username = username;
return this;
}
public User2 setPassword(String password) {
this.password = password;
return this;
}
}
@ToString(of = {"username"})
class User3{
private String username;
private String password;
public User3 setUsername(String username) {
this.username = username;
return this;
}
public User3 setPassword(String password) {
this.password = password;
return this;
}
}
@ToString(callSuper=true, includeFieldNames=false)
class User4{
private String username;
private String password;
public User4 setUsername(String username) {
this.username = username;
return this;
}
public User4 setPassword(String password) {
this.password = password;
return this;
}
}
输出结果
User1(username=admin, password=123)
User2(password=123)
User3(username=admin)
User4(super=com.test.User4@6536e911, admin, 123)
@EqualsAndHashCode
修饰JavaBean,默认情况下,会使用所有非静态(non-static)和非瞬态(non-transient)属性来生成equals和hasCode
代码实现
public class Test {
public static void main(String[] args) {
User1 user11 = new User1().setUsername("admin").setPassword("123");
User1 user12 = new User1().setUsername("admin1").setPassword("123");
System.out.println(user11.equals(user12));
User2 user21 = new User2().setUsername("admin").setPassword("123");
User2 user22 = new User2().setUsername("admin1").setPassword("123");
System.out.println(user21.equals(user22));
User3 user31 = new User3().setUsername("admin").setPassword("123");
User3 user32 = new User3().setUsername("admin").setPassword("1234");
System.out.println(user31.equals(user32));
}
}
@EqualsAndHashCode
class User1{
private String username;
private String password;
public User1 setUsername(String username) {
this.username = username;
return this;
}
public User1 setPassword(String password) {
this.password = password;
return this;
}
}
@EqualsAndHashCode(exclude = {"username"})
class User2{
private String username;
private String password;
public User2 setUsername(String username) {
this.username = username;
return this;
}
public User2 setPassword(String password) {
this.password = password;
return this;
}
}
@EqualsAndHashCode(of = {"username"})
class User3{
private String username;
private String password;
public User3 setUsername(String username) {
this.username = username;
return this;
}
public User3 setPassword(String password) {
this.password = password;
return this;
}
}
输出结果
false
true
true
@Getter
可以修饰JavaBean,也可以修饰属性,生成相应属性的get()方法
代码实现
public class Test {
public static void main(String[] args) {
User user = new User();
System.out.println("username:" + user.getUsername());
System.out.println("password:" + user.getPassword());
}
}
@Getter
class User{
private String username = "admin";
private String password = "123";
}
输出结果
username:admin
password:123
@Setter
可以修饰JavaBean,也可以修饰属性,生成相应属性的set()方法
代码实现
public class Test {
public static void main(String[] args) {
User user = new User();
user.setUsername("admin");
user.setPassword("123");
System.out.println(user);
}
}
@Setter
@ToString
class User{
private String username;
private String password;
}
输出结果
User(username=admin, password=123)
@NonNull
修饰方法参数,自动判断参数是否为null,为null则抛出NullPointerException
代码实现
public class Test {
public static void main(String[] args) {
Test.test("");
Test.test(null);
}
public static void test(@NonNull String str) {
System.out.println("str:" + str);
}
}
输出结果
str:
Exception in thread "main" java.lang.NullPointerException: str
@NoArgsConstructor
修饰JavaBean,可以动态生成无参构造器方法
最没用的注解,没有之一!
代码实现
public class Test {
public static void main(String[] args) {
User user = new User();
System.out.println(user);
}
}
@NoArgsConstructor
class User{
private String username;
private String password;
}
输出结果
com.test.User@7bb11784
@RequiredArgsConstructor
修饰JavaBean,生成private构造方法,使用staticName选项生成指定名称的static方法,与@NonNull联用,指定那些属性是本方法参数
代码实现
public class Test {
public static void main(String[] args) {
User user = new User();
System.out.println("user:" + user);
User2 user2 = User2.of();
System.out.println("user2:" + user2);
}
}
@RequiredArgsConstructor
class User{
private String username;
private String password;
}
@RequiredArgsConstructor(staticName = "of")
class User2{
private String username;
private String password;
}
输出结果
user:com.test.User@7bb11784
user2:com.test.User2@33a10788
@AllArgsConstructor
修饰JavaBean,可以动态生成全参构造器方法
代码实现
public class Test {
public static void main(String[] args) {
User user = new User("admin", "123");
System.out.println("user:" + user);
}
}
@AllArgsConstructor()
@ToString
class User{
private String username;
private String password;
}
输出结果
user:User(username=admin, password=123)
@Data
修饰JavaBean,集合了@ToString、@EqualsAndHashCode、@Getter/@Setter、@RequiredArgsConstructor的所有特性,如果属性中
代码实现
public class Test {
public static void main(String[] args) {
User user = new User();
User user1 = new User();
System.out.println(user.equals(user1));
user.setUsername("admin");
System.out.println("admin:" + user.getUsername());
System.out.println("user:" + user);
User2 user2 = User2.of("admin2");
System.out.println("user2:" + user2);
}
}
@Data
class User{
private String username;
private String password;
}
@Data(staticConstructor = "of")
class User2{
@NonNull
private String username;
private String password;
}
输出结果
true
admin:admin
user:User(username=admin, password=null)
user2:User2(username=admin2, password=null)
@Value
修饰JavaBean,和@Data类似,区别在于它会把所有成员变量默认定义为private final修饰,并且不会生成set方法
代码实现
public class Test {
public static void main(String[] args) {
User user = new User("admin", "123");
System.out.println(user);
}
}
@Value
class User{
private String username;
private String password;
}
输出结果
User(username=admin, password=123)
@Slf4j
修饰JavaBean,当项目中使用Slf4j日志架构的时候自动创建log日志实例
@Slf4j主要用于替换如下代码
private static final Logger log = LoggerFactory.getLogger(当前类名.class);
Slf4j Maven 坐标
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
代码实现
@Slf4j
public class Test {
public static void main(String[] args) {
log.info("test");
}
}
输出结果
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/maven_repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/maven_repository/org/apache/logging/log4j/log4j-slf4j-impl/2.10.0/log4j-slf4j-impl-2.10.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
09:59:36.413 [main] INFO com.test.Test - test
@Log4j
修饰JavaBean,当项目中使用Log4j日志架构的时候自动创建日志实例
@Log4j主要用于替换如下代码
private static final Logger log = Logger.getLogger(当前类名.class);
Log4j Maven 坐标
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
在项目的resources目录下,创建log4j.properties文件,内容如下:
# Global logging configuration 开发时候建议使用 debug
#log4j.rootLogger=debug, stdout
log4j.rootLogger=info, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
代码实现
@Log4j
public class Test {
public static void main(String[] args) {
log.info("test");
}
}
输出结果
2019-12-23 10:34:46,566 INFO [com.test.Test] - test
@Log4j2
修饰JavaBean,当项目中使用Log4j日志架构的时候自动创建日志实例
@Log4j主要用于替换如下代码
private static final Logger log = Logger.getLogger(当前类名.class);
Log4j Maven 坐标
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
代码实现
@Log4j2
public class Test {
public static void main(String[] args) {
log.info("test");
}
}
输出结果
10:49:52.742 [main] INFO com.test.Test - test
@Synchronized
修饰方法,自动生成同步代码块锁
@Sychronized 是一个处理线程安全问题的annotation, 类似 synchronized关键字,不同点在于关键字synchronized是锁定当前对象(this指针) , 而@Synchronized则会锁定一个private的常量。如果当前类中没有这个常量,就会自动生成一个。
代码实现
public class Test {
@Synchronized
public static void test1() {
System.out.println("test1");
}
@Synchronized
public void test2() {
System.out.println("test2");
}
@Synchronized("readLock")
public void test3() {
System.out.println("test3");
}
}
相当于
public class Test {
private static final Object $LOCK = new Object[0];
private final Object $lock = new Object[0];
private final Object readLock = new Object();
public static void test1() {
synchronized($LOCK) {
System.out.println("test1");
}
}
public void test2() {
synchronized($lock) {
System.out.println("test2");
}
}
public void test3() {
synchronized(readLock) {
System.out.println("test3");
}
}
}
@Cleanup
修饰流变量,自动调用close()方法
代码实现
public class Test {
public static void main(String[] args) throws IOException {
@Cleanup InputStream in = new FileInputStream(args[0]);
@Cleanup OutputStream out = new FileOutputStream(args[1]);
}
}
Lombok 高级注解 详解
@Accessors(chain=true)
修饰JavaBean,链式风格,在调用set方时,返回当前实例
代码实现
public class Test {
public static void main(String[] args) {
User user = new User().setUsername("admin").setPassword("123");
System.out.println(user);
}
}
@Setter
@ToString
@Accessors(chain = true)
class User{
private String username;
private String password;
}
输出结果
User(username=admin, password=123)
@Builder
修饰JavaBean,构建者模式,不可与@NoArgsConstructor同时使用
代码实现
public class Test {
public static void main(String[] args) {
User user = User.builder().username("admin").password("123").build();
System.out.println(user);
}
}
@Builder
@ToString
class User{
private String username;
private String password;
}
输出结果
User(username=admin, password=123)
@Delegate
修饰JavaBean,代理模式
代码实现
@AllArgsConstructor
public abstract class FilterRestTemplate implements RestOperations {
@Delegate
protected volatile RestTemplate restTemplate;
}
/*********************************************/
public abstract class FilterRestTemplate implements RestOperations {
protected volatile RestTemplate restTemplate;
protected FilterRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
return restTemplate.getForObject(url,responseType,uriVariables);
}
@Override
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
return restTemplate.getForObject(url,responseType,uriVariables);
}
@Override
public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
return restTemplate.getForObject(url,responseType);
}
@Override
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
return restTemplate.getForEntity(url,responseType,uriVariables);
}
//其他实现代码略。。。
}
参考:
https://www.cnblogs.com/heyonggang/p/8638374.html
https://www.cnblogs.com/pascall/p/10281169.html