lombok插件的使用和技巧

1、为什么?

在过往的Java项目中,充斥着太多不友好的代码:POJO的getter/setter/toString;异常处理;I/O流的关闭操作等等,这些样板代码既没有技术含量,又影响着代码的美观,于是Lombok应运而生。Lombok能够达到的效果就是在源码中不需要写一些通用的方法,但是在编译生成的字节码文件中会帮我们生成这些方法,减少代码冗余。

2、使用示例

常见简单示例:

    @Data
    public class Basic {
    		private String name;
    }
    //@Data代替了手动设置getter setter tostring

不常见、技巧性示例:

  • @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;
    }
  • @RequiredArgsConstructor 相较于@AllArgsConstructor只会构造注入 final 注释的属性,推荐使用
    @RestController
    @RequiredArgsConstructor
    @RequestMapping("/user")
    @Api(value = "user", tags = "用户管理模块")
    public class SysUserController {
    	private final SysUserService userService;
    }
  • @SneakyThrows抛出异常
    @SneakyThrows
    private void checkCode(ServerHttpRequest request) {
       String code = request.getQueryParams().getFirst("code");
       if (StrUtil.isBlank(code)) {
       	throw new ValidateCodeException("验证码不能为空");
       }
       redisTemplate.delete(key);
    }
    // 不使用@SneakyThrows就要加抛出
    private void checkCode(ServerHttpRequest request) throws ValidateCodeException {
       String code = request.getQueryParams().getFirst("code");
       if (StrUtil.isBlank(code)) {
       	throw new ValidateCodeException("验证码不能为空");
       }
    }
  • @UtilityClass 工具类再也不用定义static的方法了,直接就可以Class.Method 使用
    @UtilityClass
    public class xxUtil {
        public String sayHello() {
            return "hello world!";
        }
    }
    //在任意代码中可以直接使用
    public static void main(String[] args) {
        System.out.println(xxUtil.sayHello);
    }
  • @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); 

3、总结

这些注解可以大大简化代码,让代码更美观,建议实际开发中多多应用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

出世&入世

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

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

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

打赏作者

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

抵扣说明:

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

余额充值