Eliminate verbose java code with Lombok

Why use Lombok

In the development process, we usually define a large number of JavaBeans, and then use the IDE to generate the constructor, getter, setter, equals, hashcode, toString methods of its properties. When we want to add properties or change a property, such as naming , types, etc., all need to regenerate these methods mentioned above. Such duplication of labor is meaningless, and the annotations in Lombok can easily solve these problems.

Introduction to Lombok

Lombok is a tool that can help us simplify and eliminate some necessary but bloated Java code through a simple form of annotation. By using the corresponding annotation, the corresponding method can be generated when compiling the source code. Official address: https://projectlombok.org/ , github address: https://github.com/rzwitserloot/lombok .

lombok install

eclipse install lombok

  1. Double-click the downloaded JAR package to install lombok
  2. eclipse/myeclipse manually install lombok

    1. Copy lombok.jar to the folder where myeclipse.ini / eclipse.ini is located
    2. Open eclipse.ini/myeclipse.ini, insert the following two lines at the end and save:
      -Xbootclasspath/a:lombok.jar
      -javaagent:lombok.jar
    3. restart eclipse/myeclipse

IntelliJ IDEA installation method

  1. add maven dependencies

    <!--lombok-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.18</version>
    </dependency>
  2. A plugin needs to be added to the idea to support Lombok

    lombok Plugin
    image

    lombok annotation

    There are not many annotations provided by lombok, you can refer to the official video explanation and official documentation.
    Lombok annotation online help document: http://projectlombok.org/features/index .
    Here are a few lombok annotations I commonly use:
    @Data : Annotated on the class; provides the getting and setting methods of all properties of the class, and also provides equals, canEqual, hashCode, toString methods
    @Setter: annotated on the property; provide a setting method for the property
    @Getter: annotated on the property; provide a getting method for the property
    @Log4j: annotated on the class; provide a class with a property named log The log4j log object
    @NoArgsConstructor: Annotated on the class; provides a no-argument constructor for
    the class @AllArgsConstructor: Annotated on the class; provides a full-parameter constructor for the class

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324654318&siteId=291194637