Lombok 注解简洁说明

本文详细介绍了Lombok注解的功能和使用方法,包括@Data、@Setter、@Getter、@NotNull等常见注解,以及@Builder、@NoArgsConstructor、@AllArgsConstructor等高级注解。通过实例展示了如何简化Java类的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Lombok注解:

@Data:注解在类上,将类提供的所有属性都添加get、set方法,并添加、equals、canEquals、hashCode、toString方法

@Setter:注解在类上,为所有属性添加set方法、注解在属性上为该属性提供set方法

@Getter:注解在类上,为所有的属性添加get方法、注解在属性上为该属性提供get方法

@NotNull:在参数中使用时,如果调用时传了null值,就会抛出空指针异常

@Synchronized 用于方法,可以锁定指定的对象,如果不指定,则默认创建一个对象锁定

@Log作用于类,创建一个log属性

@Builder:使用builder模式创建对象

@NoArgsConstructor:创建一个无参构造函数

@AllArgsConstructor:创建一个全参构造函数, 替代@Autowired构造注入,多个bean 注入时更加清晰

@Slf4j
@Configuration
@AllArgsConstructor
public class RouterFunctionConfiguration {
   private final HystrixFallbackHandler hystrixFallbackHandler;
   private final ImageCodeHandler imageCodeHandler;
   
}


@Slf4j
@Configuration
public class RouterFunctionConfiguration {
   @Autowired
   private  HystrixFallbackHandler hystrixFallbackHandler;
   @Autowired
   private  ImageCodeHandler imageCodeHandler;
}

@ToString:创建一个toString方法

@Accessors(chain = true)使用链式设置属性,set方法返回的是this对象。

@RequiredArgsConstructor:创建对象, 例: 在class上添加@RequiredArgsConstructor(staticName = “of”)会创建生成一个静态方法

@UtilityClass:工具类再也不用定义static的方法了,直接就可以Class.Method 使用

@UtilityClass
public class Utility {

    public String getName() {
        return "name";
    }
}

public static void main(String[] args) {
    System.out.println(Utility.getName());
}

@ExtensionMethod:设置父类

@FieldDefaults:设置属性的使用范围,如private、public等,也可以设置属性是否被final修饰。

@SneakyThrows

@SneakyThrows
private void checkCode(ServerHttpRequest request) {
   String code = request.getQueryParams().getFirst("code");

   if (StrUtil.isBlank(code)) {
   	throw new ValidateCodeException("验证码不能为空");
   }

   redisTemplate.delete(key);
}


// 不使用就要加这个抛出
private void checkCode(ServerHttpRequest request) throws ValidateCodeException {
   String code = request.getQueryParams().getFirst("code");

   if (StrUtil.isBlank(code)) {
   	throw new ValidateCodeException("验证码不能为空");
   }
}

@EqualsAndHashCode:重写equals和hashcode方法。

@Cleanup: 清理流对象,不用手动去关闭流

@Cleanup
OutputStream outStream = new FileOutputStream(new File("text.txt"));
@Cleanup
InputStream inStream = new FileInputStream(new File("text2.txt"));
byte[] b = new byte[65536];
while (true) {
   int r = inStream.read(b);
   if (r == -1) break;
   outStream.write(b, 0, r); 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大痴小乙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值