Gio*_*Poe 3 java annotations autowired spring-boot
我看过一些教程,他们使用不同的语法来完成同样的事情。一旦创建学生对象的 POST 请求通过控制器传入,服务层就会使用这两种方法注入存储库。
方法一:
@Service
@AllArgsConstructor
@Transactional
public class StudentService {
private final StudentRepository studentRepo;
// complete service code using studentRepo
}
Run Code Online (Sandbox Code Playgroud)
以及方法2:
@Service
public class StudentService {
@Autowire
private StudentRepository studentRepo;
// complete service code using studentRepo
}
Run Code Online (Sandbox Code Playgroud)
我读到它与构造函数和字段注入有关,但我真的不明白这种语法如何解决差异。有什么解释或资源可以让我更好地理解吗?先感谢您!
您堆叠了很多框架,这增加了混乱。造成混乱的原因可能是您使用的是 Lombok。它@AllArgsConstructor会自动添加一个构造函数,其中包含构造服务实例所需的所有参数。
@AllArgsConstructor为类中的每个字段生成一个带有 1 个参数的构造函数。标记为 的字段@NonNull会导致对这些参数进行空检查。- 来源:Lombok 文档
使用@AllArgsConstructor有效地生成以下类
@Service
@Transactional
public class StudentService {
private final StudentRepository studentRepo;
public StudentService(StudentRepository studentRepo) {
this.studentRepo=studentRepo;
}
// complete service code using studentRepo
}
Run Code Online (Sandbox Code Playgroud)
现在,由于此类只有一个构造函数,Spring 将使用它来进行依赖项注入。这称为基于构造函数的依赖注入。
@Service
@Transactional
public class StudentService {
@Autowire
private StudentRepository studentRepo;
// complete service code using studentRepo
}
Run Code Online (Sandbox Code Playgroud)
而这称为基于字段的依赖注入。
恕我直言,您应该更喜欢基于构造函数的依赖注入,原因很简单,它非常易于使用并且就在您面前。您可以轻松地测试它,而使用字段注入编写单元测试很困难(呃),因为您需要反射来注入字段。
另请参阅Java 中的依赖注入,以获取对不同依赖注入样式的更全面的解释。
| 归档时间: |
|
| 查看次数: |
9782 次 |
| 最近记录: |