@RequiredArgsConstructor detailed explanation

1. What is @RequiredArgsConstructor?

@RequiredArgsConstructor is an annotation of Lombok, which simplifies our @Autowired writing. When we write the Controller layer or Service layer, we always need to inject many mapper interfaces or services Interface, if each interface is written with @Autowired, it will look very cumbersome. @RequiredArgsConstructor annotation can replace @Autowired annotation

2. How to use @RequiredArgsConstructor?

Guide package

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

use

Write @RequiredArgsConstructor on the class

 important point

1. The declared variables must be modified with final

2. Assign values ​​to attributes based on the constructor method, and the container performs dependency injection on it by calling the constructor method of the class.

3. The difference between @AllArgsConstructor and @RequiredArgsConstructor

  • @AllArgsConstructor generates a constructor containing all fields,If @Value injection is used, @Value injection will be invalid.The reason is because The @Value annotation is assigned through the set method of the object. The execution of the constructor is still before the set method, so using the variable in the constructor will cause the variable to be null.
  • @RequiredArgsConstructor will generate a constructor for each final field or non-null field of the class
  • Summary: Both @AllArgsConstructor and @RequiredArgsConstructor can be used to replace the @Autowired writing method. The difference is that @RequiredArgsConstructor must have final modification. If there is @Value annotation, the @RequiredArgsConstructor modification can be successfully injected, but the @AllArgsConstructor modification will fail to be injected.

 

Guess you like

Origin blog.csdn.net/qq_36138652/article/details/131812722