Lombok不常见但实用的注解
资料参考地址1:
@SneakyThrows注解
资料参考地址2:
Lombok之@Cleanup使用
资料参考地址3:
lombok 实验性注解之 @UtilityClass
@SneakyThrows
为了消除遇到Exception异常时必须try catch 或向上抛处理的模板代码
示例代码
import lombok.SneakyThrows;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* SneakyThrows是为了消除这样的模板代码
* https://blog.csdn.net/qq_22162093/article/details/115486647
* @author : lyn
*/
public class SneakyThrowsTest {
/**
* 使用前必须用try catch 包一层
*/
private Date strToDate1(String str) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 使用@SneakyThrows后简洁了很多
*/
@SneakyThrows
private Date strToDate2(String str) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(str);
}
}
@UtilityClass
作用于类,将类标记为 final,并且类、内部类中的方法、字段都标记为 static
并私有了构造方法,一般用在工具类上
编译前
@UtilityClass
public class UtilityClassTest {
private String name;
public void methodOne(){
System.out.println("");
}
}
编译后
public final class UtilityClassTest {
private static String name;
private UtilityClassTest() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
public static void methodOne() {
System.out.println("");
}
}
@Cleanup
清理流对象,不用手动去关闭流,多么优雅
编译前
@Cleanup Reader fileReader = new FileReader("D:\\code.txt");
编译后
try {
Reader fileReader = new FileReader("D:\\code.txt");
if (Collections.<Reader>singletonList(fileReader).get(0) != null)
fileReader.close();
} catch (Throwable $ex) {
throw $ex;
}
Collections.singletonList被限定只被分配一个内存空间,也就是只能存放一个元素的内容
Collections.singletonList的作用和使用方法
@AllArgsConstructor
与private final 结合使用
替代@Autowired构造注入,多个bean 注入时更加清晰,但有循环依赖的问题
@AllArgsConstructor
@Slf4j
@Component
@AllArgsConstructor
public class CustomAuthenticationSuccessEventHandler implements AuthenticationSuccessHandler {
private final OperationLogHandler operationLogHandler;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现