一、@Resource注入
@Resource
private TestService testService;
二、@Autowired注入(字段注入)
字段注解直接注入,是最常用的注入方式
@Autowired
private TestService testService;
三、setter方法注入
private TestService testService;
@Autowired
public void setTestService(TestService testService) {
this.testService = testService;
}
四、构造方法注入(final注入),更推荐这种方式
private final TestService testService;
public TestController(TestService testService) {
this.testService = testService;
}
ps:有种说法是字段注入是在运行时依赖注入,当发生循环依赖时,构造方法注入可以在启动时就报循环依赖异常立刻被开发者发现,但是字段注入不那么明显;对此我试验了一下(springboot2.6.13版本),两种注入在启动时都会报循环依赖异常,不知道是否在老版本验证的该说法。