RequiredArgsConstructor(onConstructor = @__(@Autowired)):
时间: 2023-08-26 20:11:09 浏览: 192
`@RequiredArgsConstructor(onConstructor = @__(@Autowired))` 是一个Lombok注解,它可以为类的非静态字段生成构造函数,并在构造函数中自动注入依赖。这个注解会为带有 `@NonNull` 注解的字段生成参数,并将它们作为构造函数的参数。它的作用是简化构造函数的编写,避免手动添加大量的 `@Autowired` 注解和参数。
举个例子,如果有一个类如下所示:
```java
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MyClass {
private final MyDependency myDependency;
private final AnotherDependency anotherDependency;
private final YetAnotherDependency yetAnotherDependency;
// ...
}
```
在这个例子中,`MyClass` 类有三个非静态字段 `myDependency`、`anotherDependency` 和 `yetAnotherDependency`。使用 `@RequiredArgsConstructor(onConstructor = @__(@Autowired))` 注解后,Lombok会为这些字段生成一个带有自动注入的构造函数,如下所示:
```java
public MyClass(MyDependency myDependency, AnotherDependency anotherDependency, YetAnotherDependency yetAnotherDependency) {
this.myDependency = myDependency;
this.anotherDependency = anotherDependency;
this.yetAnotherDependency = yetAnotherDependency;
}
```
这样,在使用这些依赖时,就不需要手动添加 `@Autowired` 注解了。
阅读全文