Installation and use of Java development artifact Lombok

install

Lombok installation is divided into two parts: the installation of Idea plug-in and the import of pom file in maven.

Installation of Idea plug-in

Click settings, select plug-ins, search Lombok (Networking required) in the plug-in configuration of Idea or download local installation on the official website, and click initialize installation

You can also see the annotations it supports in the description of the plug-in.

Import of pom file in maven

The second step is to introduce dependencies in pom. Currently, the smallest version is 1.18.10.

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
</dependency>

If you create a Spring Boot project through Idea, you can directly select Lombok in the "Developer Tool" when creating the project.

After completing the above two steps, you can use the artifact in your code.

use

This is the supported annotation given on the official website. Here we can also check: https://projectlombok.org/features/all

Common notes and their introduction are given here:

val

Use val as the type declared by the local variable instead of the actual write type. When you do this, the type is inferred from the initialization expression.

public Map<String, String> getMap() {
	val map = new HashMap<String, String>();
	map.put("1", "a");
	return map;
}

The effect is as follows:

public Map<String, String> getMap() {
    HashMap<String, String> map = new HashMap();
    map.put("1", "a");
    return map;
}

In other words, Lombok can help you infer specific types in local variables, but it can only be used in local variables.

@Data

@Data is one of the most commonly used annotations. Annotation on a class, it provides getter/setter methods for all properties of the class, as well as equals, canEqual, hashCode and toString methods.

Developers don't need to write the corresponding methods, and Lombok will help you generate all the above methods.

The example of using @ Data is as follows. The most intuitive thing is not to write getter/setter methods.

@Data
public class Demo {
	private int id;
	private String remark;
}

Let's see what this class looks like after compilation.

public class Demo {
    private int id;
    private String remark;

    public Demo() {
    }

    public int getId() {
        return this.id;
    }

    public String getRemark() {
        return this.remark;
    }

    public void setId(final int id) {
        this.id = id;
    }

    public void setRemark(final String remark) {
        this.remark = remark;
    }

    public boolean equals(final Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof Demo)) {
            return false;
        } else {
            Demo other = (Demo)o;
            if (!other.canEqual(this)) {
                return false;
            } else if (this.getId() != other.getId()) {
                return false;
            } else {
                Object this$remark = this.getRemark();
                Object other$remark = other.getRemark();
                if (this$remark == null) {
                    if (other$remark != null) {
                        return false;
                    }
                } else if (!this$remark.equals(other$remark)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(final Object other) {
        return other instanceof Demo;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        int result = result * 59   this.getId();
        Object $remark = this.getRemark();
        result = result * 59   ($remark == null ? 43 : $remark.hashCode());
        return result;
    }

    public String toString() {
        return "Demo(id="   this.getId()   ", remark="   this.getRemark()   ")";
    }
}

The official website gives more details. Only a part is shown here. For example, the following figure is an example given by the official website:

Link: https://projectlombok.org/features/Data

@Getter/@Setter

Act on the attribute and provide getter/setter methods for the attribute;
Function on the class, provide getter/setter methods for all properties of the class, and provide default construction methods.

An example of using @ Getter/@Setter is as follows:

public class GetterSetterExample {
  @Getter @Setter private int age = 10;
  @Setter(AccessLevel.PROTECTED) private String name;
  @Override public String toString() {
    return String.format("%s (age: %d)", name, age);
  }
}

This is what it looks like after compilation:

public class GetterSetterExample {
  private int age = 10;
  private String name;
  
  @Override public String toString() {
    return String.format("%s (age: %d)", name, age);
  }
  
  public int getAge() {
    return age;
  }
  
  public void setAge(int age) {
    this.age = age;
  }
  
  protected void setName(String name) {
    this.name = name;
  }
}

Other examples will not be shown. You can check the details on the official website. Only the functions are given here.

@Log4j

Acts on a class and provides the class with a log4j log object with the attribute log.

@Log4j
public class Demo {

}

This attribute is generally used on business processing classes such as Controller and Service. The same as this annotation is @ Log4j2, as the name suggests, for Log4j2.

@AllArgsConstructor

Act on a class and provide it with a constructor containing all parameters. Note that the default constructor will not be provided at this time.

@AllArgsConstructor
public class Demo {
	private int id;
	private String remark;
}

The effect is as follows:

public class Demo {
    private int id;
    private String remark;

    public Demo(final int id, final String remark) {
        this.id = id;
        this.remark = remark;
    }
}

@NoArgsConstructor

Acts on a class and provides a parameterless constructor.

It can be used with @ AllArgsConstructor at the same time. At this time, two construction methods will be generated: no parameter construction method and all parameter construction method.

@EqualsAndHashCode

Generate class and equal code, and act on equal and equal methods.

See the initial @ Data effect for specific effects, or refer to the official website.

@NonNull

It acts on the property and provides a non null check on this parameter. If the parameter is null, a null pointer exception will be thrown.

usage method:

public class Demo {
	@NonNull
	private int id;
	private String remark;
}

@RequiredArgsConstructor

Acting on the class, all member variables with @ NonNull annotation or final modification in the class are used as parameters to generate construction methods.

@Cleanup

Acts on a variable to ensure that the resource represented by the variable will be automatically closed. The close() method of the resource is called by default. If the resource has other closing methods, you can use @ Cleanup("methodName") to specify.

public void jedisExample(String[] args) {
    try {
        @Cleanup Jedis jedis = redisService.getJedis();
    } catch (Exception ex) {
        logger.error("Jedis abnormal:",ex)
    }
}

The effect is equivalent to:

public void jedisExample(String[] args) {
    Jedis jedis= null;
    try {
        jedis = redisService.getJedis();
    } catch (Exception e) {
        logger.error("Jedis abnormal:",ex)
    } finally {
        if (jedis != null) {
            try {
                jedis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

@ToString

Act on the class and generate a toString method containing all parameters. See toString method in @ Data.

@Value

Acting on a class, it will generate all parameter constructor methods, getter methods, equals, hashCode and toString methods.

Compared with @ Data, it has more full parameter construction methods and less default construction methods, setter methods and canEqual methods.

The note should be noted that the field will be decorated with final. Personally, I feel that it is out of control and is not recommended.

@SneakyThrows

Acting on the method is equivalent to adding a try catch process to the code in the method to catch exceptions. Lombok. Is used in catch Snakythrow (E) throws an exception. Use @ SneakyThrows(BizException.class) to specify the specific exception to throw.

@SneakyThrows
public int getValue(){
	int a = 1;
	int b = 0;
	return a/b;
}

The effect is as follows:

public int getValue() {
    try {
        int a = 1;
        int b = 0;
        return a / b;
    } catch (Throwable var3) {
        throw var3;
    }
}

@Synchronized

Acting on class methods or instance methods, the effect is the same as synchronized.

The difference lies in different lock objects. For class methods and instance methods, the lock objects of Synchronized keyword are class object and this object of class respectively, while the lock objects of @ Synchronized are private static final object lock and private final object lock respectively. You can also specify a lock object.

public class FooExample { 
	private final Object readLock = new Object(); 
	
	@Synchronized 
	public static void hello() { 
	    System.out.println("world");   
	} 
	
	@Synchronized("readLock") 
	public void foo() { 
	  System.out.println("bar"); 
	} 
}

The effect is equivalent to the following:

public class FooExample { 
  private static final Object $LOCK = new Object[0]; 
  private final Object readLock = new Object(); 

  public static void hello() { 
    synchronized($LOCK) { 
      System.out.println("world"); 
    } 
  }   

  public void foo() { 
    synchronized(readLock) { 
        System.out.println("bar");   
    } 
  } 
}

@Builder

If you like to use Builder's streaming operation, then @ Builder may be your favorite annotation.

usage method:

@Builder
public class Demo {
	private int id;
	private String remark;
}

The effect is as follows:

public class Demo {
    private int id;
    private String remark;

    Demo(final int id, final String remark) {
        this.id = id;
        this.remark = remark;
    }

    public static Demo.DemoBuilder builder() {
        return new Demo.DemoBuilder();
    }

    public static class DemoBuilder {
        private int id;
        private String remark;

        DemoBuilder() {
        }

        public Demo.DemoBuilder id(final int id) {
            this.id = id;
            return this;
        }

        public Demo.DemoBuilder remark(final String remark) {
            this.remark = remark;
            return this;
        }

        public Demo build() {
            return new Demo(this.id, this.remark);
        }

        public String toString() {
            return "Demo.DemoBuilder(id="   this.id   ", remark="   this.remark   ")";
        }
    }
}

We can see that DemoBuilder class is provided inside this class to handle specific streaming operations. At the same time, the construction method of full parameters is provided.

Keywords: Java Spring Boot intellij-idea

Added by emceej on Tue, 22 Feb 2022 14:46:03 +0200