Lombok-入门(效率开发)

文章目录

      • Lombok
        • 去Autowired注解
        • val
        • @NonNull-空值校验
        • @Cleanup-自动关闭资源
        • @Getter/@Setter
        • @ToString
        • @EqualsAndHashCode
        • @~Constructor-构造函数
        • @Data
        • @Value-不可变类
        • @Builder-使用建造者模式来创建对象
          • @Accessors(chain = true)-开启链式编程
          • @Accessors(fluent = true)-开启链式编程,省略给对象赋值和取值时候得set、get前缀
        • @SneakyThrows-自动抛出异常
        • @Synchronized-锁,线程安全同步访问
        • @With-对象克隆
        • @Getter(lazy=true)
        • @Log-直接生成日志对象
        • @Slf4j

Lombok

官方文档:
Stable — 稳定 (projectlombok.org)

  • 增强代码,省去常规代码,编译自动生成代码,提高开发效率。
  
<dependency>  
    <groupId>org.projectlombokgroupId>  
    <artifactId>lombokartifactId>  
    <version>1.18.20version>  
dependency>
去Autowired注解

Required Args Constructor 使用说明:
构造函数会自动调用。这样就可以方便地使用依赖注入功能,而不需要手动创建和装配bean
用组件测试:

@Component  
@RequiredArgsConstructor(onConstructor = @__(@Autowired))  
@SpringBootTest  
public class MyService {    
private final ArticleService articleService;  
    @Test  
    public void doSomething() {  
        List<Article> list = articleService.list();  
        System.out.println(JSON.toJSON(list));  
    }  
}

开发使用:
在ServiceImpl(实现业务逻辑)中

  • 自动生成一个包含所有非null属性字段的构造函数,并且在构造函数上添加@Autowired注解,以便Spring框架可以自动注入依赖。同时,由于这些注解都是编译时注解,因此它们的性能开销也非常小。
@Service  
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
val

val可以取代任意类型作为局部变量。

@Test  
public void cs1(){  
    // Lombok的val使用  
    val cs = new ArrayList<String>();  
    cs.add("1");  
    System.out.println(cs);  
    val cs1 = new HashMap<String,String>();  
    cs1.put("1","1");  
    System.out.println(cs1);  
}
@NonNull-空值校验

在方法上使用进行空值校验。

public NonNullTest(@NonNull String name) {  
    this.name = name;  
}
@Cleanup-自动关闭资源
@Test  
public void cs3() throws IOException {  
    // Lombok的@Cleanup使用  
    // 输入输出流,无需编写try catch和调用close()方法  
    String inStr = "Hello World!";  
    @Cleanup ByteArrayInputStream in = new ByteArrayInputStream(inStr.getBytes("UTF-8"));  
    @Cleanup ByteArrayOutputStream out = new ByteArrayOutputStream();  
    byte[] b = new byte[1024];  
    while (true) {  
        int r = in.read(b);  
        if (r == -1) break;  
        // 输入流  
        out.write(b, 0, r);  
    }  
    // 输出流  
    String outStr = out.toString("UTF-8");  
    System.out.println(outStr);  
}
@Getter/@Setter

生成getter/setter方法。

@ToString

生成toStrng方法。

@EqualsAndHashCode

生成equals,hashCode,便于比较二个对象。

@~Constructor-构造函数
  • @NoArgsConstructor:生成无参构造函数。
  • @RequiredArgsConstructor:生成包含必须参数的构造函数,使用@NonNull注解的类属性为必须参数。
  • @AllArgsConstructor:生成包含所有参数的构造函数。
@Data

@Data是一个方便使用的组合注解,是@ToString、@EqualsAndHashCode、@Getter、@Setter和@RequiredArgsConstructor的组合体。

@Value-不可变类

类无法被继承,属性无法被设置,只能使用全参构造器。

TestEntity testEntity = new TestEntity("@Value","3");
@Builder-使用建造者模式来创建对象

建造者模式+链式编程。

TestEntity build = TestEntity.builder()  
        .name("张三")  
        .age("18")  
        .build();  
System.out.println(build);
@Accessors(chain = true)-开启链式编程
@Data  
@Accessors(chain = true)  
public class TestEntity2 implements Serializable {  
    private String name;  
    private String age;  
    public static void main(String[] args) {  
        TestEntity2 testEntity2 = new TestEntity2();  
        testEntity2.setName("张三")  
               .setAge("18");  
        System.out.println(testEntity2);  
    }  
}
@Accessors(fluent = true)-开启链式编程,省略给对象赋值和取值时候得set、get前缀
@SneakyThrows-自动抛出异常
//自动抛出异常,无需处理  
//@SneakyThrows(UnsupportedEncodingException.class)  
@SneakyThrows  
public static byte[] str2byte(String str) {  
    return str.getBytes("UTF-8");  
}
@Synchronized-锁,线程安全同步访问
@Synchronized  
public static void sout(){  
    if (i>0){  
        i--;  
        System.out.println("i值为:"+i);  
    }  
}
@With-对象克隆

使用时需要指定全参构造方法。

@Getter(lazy=true)

当我们获取某一个属性比较消耗资源时,可以给@Getter添加lazy=true属性实现懒加载,会生成Double Check Lock 样板代码对属性进行懒加载。

public class GetterLazyExample {  
    @Getter(lazy = true)  
    private final double[] cached = expensive();  
  
    private double[] expensive() {  
        double[] result = new double[1000000];  
        for (int i = 0; i < result.length; i++) {  
            result[i] = Math.asin(i);  
        }  
        return result;  
    }  
  
    public static void main(String[] args) {  
        //使用Double Check Lock 样板代码对属性进行懒加载  
        GetterLazyExample example = new GetterLazyExample();  
        System.out.println(example.getCached().length);  
    }  
}
@Log-直接生成日志对象
@Log  
public class cs {  
    public static void main(String[] args) {  
        log.info("level info"); // 普通信息 
        log.warning("level warning");  // 警告
        log.severe("level severe");  // 严重警告!(错误)
    }  
}
@Slf4j

使用Lombok生成日志对象时,根据使用日志实现的不同,有多种注解可以使用。比如
@Log@Log4j@Log4j2@Slf4j等。

@Slf4j  
public class LogSlf4jExample {  
    public static void main(String[] args) {  
        log.info("level:{}","info");// 信息  
        log.warn("level:{}","warn");// 警告  
        log.error("level:{}", "error");// 错误  
    }  
}

![[Pasted image 20231220163624.png]]

你可能感兴趣的:(Java,java,Lombok,spring)