① 为什么使用

还在编写无聊枯燥又难以维护的POJO吗? 洁癖者的春天在哪里?请看Lombok!在过往的Java项目中,充斥着太多不友好的代码:POJO的getter/setter/toString;异常处理;I/O流的关闭操作等等,这些样板代码既没有技术含量,又影响着代码的美观,Lombok应运而生。首先说明一下:任何技术的出现都是为了解决某一类问题的,如果在此基础上再建立奇技淫巧,不如回归Java本身。应该保持合理使用而不滥用。

③ 常用且特殊注解

@Data

相当于下面注解的集合

  1. @Getter
  2. @Setter
  3. @RequiredArgsConstructor
  4. @ToString
  5. @EqualsAndHashCode
  6. @Value


@AllArgsConstructor

:::success

  • @AllArgsConstructor 替代@Autowired构造注入,多个bean 注入时更加清晰 ::: ```java @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; }

  1. <a name="uHAcW"></a>
  2. #### @RequiredArgsConstructor
  3. :::success
  4. - @RequiredArgsConstructor** 只会构造注入 final 注释的属性**,推荐使用
  5. :::
  6. ```java
  7. @RestController
  8. @RequiredArgsConstructor
  9. @RequestMapping("/user")
  10. @Api(value = "user", tags = "用户管理模块")
  11. public class SysUserController {
  12. private final SysUserService userService;
  13. }

@SneakyThrows

:::success

  • @SneakyThrows 抛出异常 ::: ```java @SneakyThrows private void checkCode(ServerHttpRequest request) { String code = request.getQueryParams().getFirst(“code”);

    if (StrUtil.isBlank(code)) {

    1. throw new ValidateCodeException("验证码不能为空");

    }

    redisTemplate.delete(key); }

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

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

}

  1. <a name="bCDp2"></a>
  2. #### @UtilityClass
  3. :::success
  4. **@**[**UtilityClass **](/UtilityClass )** 工具类再也不用定义static的方法了,直接就可以Class.Method 使用 **
  5. :::
  6. ```java
  7. @UtilityClass
  8. public class Utility {
  9. public String getName() {
  10. return "name";
  11. }
  12. }
  13. public static void main(String[] args) {
  14. System.out.println(Utility.getName());
  15. }

@Cleanup

:::success

  • @CleanUp: 清理流对象,不用手动去关闭流,多么优雅 :::
    1. @Cleanup
    2. OutputStream outStream = new FileOutputStream(new File("text.txt"));
    3. @Cleanup
    4. InputStream inStream = new FileInputStream(new File("text2.txt"));
    5. byte[] b = new byte[65536];
    6. while (true) {
    7. int r = inStream.read(b);
    8. if (r == -1) break;
    9. outStream.write(b, 0, r);
    10. }