Background analysis
In practice java All of the projects we created pojo Classes almost always add set/get/toString And so on , All logging related classes may need to create objects such as logs , These boilerplate codes have no technical content , It also affects the beauty of the code , At the same time, the repeated coding process will increase our workload . here Lombok emerge as the times require .
lombok brief introduction
summary
Lombok It's a third party Java library , It's automatically inserted into the editor and build tool ,Lombok Provides a useful set of comments , It is used to tell the compiler tools in the compilation process , In the process of compiling source code into bytecode , Add some quantity template code to bytecode .
Common annotation analysis
- @Setter Used to generate setter Method , It doesn't contain final Modify properties .
- @Getter Used to generate getter Method .
- @ToString Used to add toString Method .
- @EqualsAndHashCode Used to describe a class for , Generate hashCode and equals Method .
- @NoArgsConstructor Used to generate parameterless constructors for described classes .
- @AllArgsConstructor Used to generate a constructor for the described class that contains all the fields in the class .
- @Data Used to generate setter/getter、equals、canEqual、hashCode、toString Method , If final attribute , Will not generate setter Method .
- @Slf4J Used to add a log property object to the described class .
lombok install
idea Installation configuration in
First step : open idea Settings window for , find plugins menu , Search for lombok Installation , As shown in the figure :
The second step : Start annotation processing , As shown in the figure :
The third step : restart idea( Optional , yes , we have idea Version needs to be ).
lombok stay maven Application in project
First step : add to lombok rely on .
(http://mvnrepository.com This link can search for coordinates )
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>annotationProcessor</scope>
</dependency>
The second step : Apply on class lombok annotation .
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Brand {
private Integer id;
private String name;
private String remark;
private Date createdTime;
}
The third step : Write unit test class detection Lombok Annotation application
@Slf4j
@SpringBootTest
public class GoodsTests{
@Test
void testGoods(){
Goods g=new Goods();
g.setId(100L);
g.setName("Lombok");
log.info("id The value of is {}",g.getId());
log.info("name The value of is {}",g.getName());
}
}
summary (Summary)
This section is mainly about lombok Did an analysis , install and configure , And combined with the actual project to explain lombok Application scenarios and specific application process of .