> ## Content Index
> Fetch the complete content index at: https://lucent.blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# lombok插件的使用和技巧
- URL: https://lucent.blog/lombokcha-jian-de-shi-yong-he-ji-qiao/
- Published: 2021-11-17T07:41:16.000Z
- Updated: 2023-11-14T02:30:13.000Z
- Author: Lucent

#### 1.为什么？

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

#### 2.使用示例

##### 常见简单示例：

```java
@Data
public class Basic {
		private String name;
}

//@Data代替了手动设置getter setter tostring

```

##### 不常见、技巧性示例：

- `@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;
}

```

- `@RequiredArgsConstructor` 相较于`@AllArgsConstructor`只会构造注入 final 注释的属性，推荐使用

```java
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@Api(value = "user", tags = "用户管理模块")
public class SysUserController {
	private final SysUserService userService;
}

```

- `@SneakyThrows`抛出异常

```java
@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 使用

```java
@UtilityClass
public class xxUtil {

    public String sayHello() {
        return "hello world!";
    }
}

//在任意代码中可以直接使用
public static void main(String[] args) {
    System.out.println(xxUtil.sayHello);
}

```

- `@CleanUp` 清理流对象,不用手动去关闭流

```java
@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.总结

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