Learn Spring Boot: (15) Use Lombok to code elegantly

foreword

Lombokis a Java™utility that can be used to help developers eliminate Java verbosity, especially for simple Java objects (POJOs). It does this through annotations.

text

add dependencies

Add the relevant dependencies in the pom.xml file:

<lombok.version>1.16.20</lombok.version>

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

Install the plugin

LombokBecause of the annotation form, after compiling, the corresponding method is automatically generated. In order to prevent the IDE from going crazy, you need to download a plug-in to support it.
Take idea as an example: find the plug-in and lombok plugininstall it .

Take my User entity class as an example (set, get, toString methods),

@Getter
@Setter
@ToString
public class SysUserEntity implements Serializable

After pressing the shortcut key Ctrl + F12, you can find the set, get, toString methods.

annotation

Write some common ones, and open the Jar package of the rest of the api at a glance

@Getter
@Setter
@ToString
@EqualsAndHashCode
Constructor
@AllArgsConstructor

A file containing all variables will be generated. At the same time, if the variable uses the NotNull annotation, it will check whether it is empty or not.
The constructor of all parameters will be automatically generated. The scope of the annotation is only on the entity class. The order and attributes of the parameters The order of definitions is the same.

@NoArgsConstructor

no-argument constructor

@RequiredArgsConstructor

Will generate a constructor with constants (final) and variables marked with @NotNull.

how to use

They both have three parameters that can be set to
1.String staticName() default "";

If it is set, the access modifier of the original constructor will become private , and a static constructor is added with the same parameters, the name is the name of the set string , and the access modifier is public .

  1. AnyAnnotation[] onConstructor() default {};
    Add annotations to constructors . Instructions@RequiredArgsConstructor(onConstructor=@__({@AnnotationsGoHere}))}

    For example, we need to inject multiple values ​​in the Spring project, and @Autowiredit is very , so we can use this method:

    @Service
    @RequiredArgsConstructor(onConstructor = @__(@Autowired))
    public class UserServiceImpl implements IUserService {
       private final IUserRepository userRepository;
       private final IOrderRepository orderRepository;
       ………………
  2. AccessLevel access() default lombok.AccessLevel.PUBLIC;
    constructor access modifiers;

  3. @NoArgsConstructorThere is also an annotation in the no-argument constructor. boolean force() default false;
    The author 's annotation is If {@code true}, initializes all final fields to 0 / null / false. Otherwise, a compile time error occurs.

    When set trueto , initialize all parameters to default values, otherwise compile errors.

@Data

I tried it myself, we can use @Dataannotations to have the following annotation functions: @ToString, @Getter, @Setter, @EqualsAndHashCode, @NoArgsConstructor.

Note that after@Data using and at the same time, the default no-argument constructor is invalid, if you need it, you need to reset it@AllArgsConstructor@NoArgsConstructor

@ Slf4j
//类上面注解了,直接调用 log 即可:
log.info(xxxx);
@Log

What is used java.util.logging.Logger, the variable is used directly log.

@Builder

Bulder mode builds objects.

@Cleanup
@Cleanup 
InputStream in = new FileInputStream(args[0]);
@Cleanup 
OutputStream out = new FileOutputStream(args[1]);

Automatically close the stream, equivalent to try with resource of jdk1.7

val

Type inference.

 val example = new ArrayList<String>();
 example.add("Hello, World!");

The corresponding converted code is:

 val example = new ArrayList<String>();
 example.add("Hello, World!");
@NonNull
public NonNullExample(@NonNull Person person) {
    this.name = person.getName();
 }

After conversion it is:

public NonNullExample(@NonNull Person person) {
    if (person == null) {
      throw new NullPointerException("person");
    }
    this.name = person.getName();
 }
@SneakyThrows

The translation is to throw an exception secretly

When we need to throw an exception, call it on the current method, without explicitly writing throw after the method name

@SneakyThrows(Exception.class)
@Synchronized

All the code in the method is added to a code block. The default static method uses the global lock, and the ordinary method uses the object lock. Of course, the lock object can also be specified.

private final Object lock = new Object();
@Synchronized("lock")
public void foo() {
    // Do something
}

Personally, I think this kind of reading is more troublesome, and in actual development, it is often synchronizedgranular into code blocks.

Guess you like

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