目的简化实体类的开发和结构
首先在项目中引入lombok的maven依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version><!--版本可以自己选,个人比较喜欢在仓库版本相对较高使用的人相对较多的版本;-->
<scope>provided</scope>
</dependency>
同时,如果是maven管理和构建项目的需要在maven pulgins中的maven-compiler-plugin 加入configuration的lombok的插件地址
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4 </version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
然后在IDEA中装插件
File->Sttings->plugin
装上lombok的插件
在使用lombok插件的时候发现问题:引入maven的包,装上了插件,但是编译的时候@Data注解没有生效,是因为没有讲插件激活。File->settings->Build,Execution,Deployment->Compiler->Annotation Processors中的对应所要用的项目中的复选框Enable annotation processing选上。
可以使用注解进行开发
@Data注解在类上,会为类的所有属性自动生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter方法。
@Getter/@Setter注解,此注解在属性上,可以为相应的属性自动生成Getter/Setter方法
@NonNull该注解用在属性或构造器上,Lombok会生成一个非空的声明,可用于校验参数,能帮助避免空指针。
@Cleanup该注解能帮助我们自动调用close()方法,很大的简化了代码。
@EqualsAndHashCode默认情况下,会使用所有非静态(non-static)和非瞬态(non-transient)属性来生成equals和hasCode,也能通过exclude注解来排除一些属性。
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor无参构造器、部分参数构造器、全参构造器。Lombok没法实现多种参数构造器的重载。