文章目录
Lombok
一、作用
- 简化了Model层的代码的编写
- 以前pojo类/实体类,需要自己提供set、get、toString、equals、hashCode, Lombok通过各种注解,简化了以上操作
二、注解
- @Data:会自动生成set、get、toString、equals、hashCode
- @NoArgsConstructor:自动生成无参构造
- @AllArgsConstructor:自动生成全参构造
- @Accessors(chain = true):开启链式编程
三、使用步骤
1、在IDEA里安装插件(高版本IDEA已经自动安装好,直接使用即可)
2、修改pom.xml文件,添加Lombok的jar包依赖,dependencies 标签内配置
<!--支持lombok-->
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
3、修改pojo包中的Shopping类
3.1、修改前
public class Shopping {
private Integer id;
private String name;
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Shopping{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
3.2、修改后
@Data // 自动生成 get set toString equals hashCode
@NoArgsConstructor // 自动生成无参构造
@AllArgsConstructor // 自动生成有参构造
@Accessors(chain = true) // 开启链式编程
public class Shopping {
private Integer id;
private String name;
private Double price;
}
4、创建TestLombok测试类
4.1、修改前
public class TestLombok {
@Test
public void test(){
Shopping shopping = new Shopping();
shopping.setId(1);
shopping.setName("辣条");
shopping.setPrice(2.5);
System.out.println(shopping.getId());
System.out.println(shopping.getName());
System.out.println(shopping.getPrice());
System.out.println(shopping);
}
}
4.2、修改后
public class TestLombok {
@Test
public void test02(){
Shopping shopping = new Shopping();
shopping.setId(2);
shopping.setName("可乐");
shopping.setPrice(3.5);
System.out.println(shopping.getId());
System.out.println(shopping.getName());
System.out.println(shopping.getPrice());
System.out.println(shopping);
Shopping shopping1 = new Shopping(3,"雪碧",3.5);
System.out.println(shopping1);
Shopping shopping2 = new Shopping();
// 使用 Lombok 的链式编程
shopping2.setId(4).setName("鸡爪子").setPrice(2.5);
System.out.println(shopping2);
}
}