以前spring项目中依赖注入通常都是这样的写法

@RestController
@RequestMapping("/kanbanVideo")
public class KanbanVideoController extends BaseController{

    @Autowired
    private AuthCommonService authCommonService;

}

还有一些其他写法可以参考之前我发布的一篇文章
https://gjwcode.cn/archives/i-d-e-a-zhong-m-y-b-a-t-i-s-zhu-ru-jing-gao-6-zhong-jie-jue-fang-shi
但是现在idea上会提示这种方式不推荐
image.png

idea给出的解决策略是这样的
Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies
意思就是总是使用构造器的方式强制注入。
所以我们可以将上面的代码改写成这样两种:

  1. 构造器注入
@RestController
@RequestMapping("/kanbanVideo")
public class KanbanVideoController extends BaseController{

    private final AuthCommonService authCommonService;

    @Autowired
    public KanbanVideoController(AuthCommonService authCommonService){
        this.authCommonService = authCommonService;
    }
}

2.set方法注入

@RestController
@RequestMapping("/kanbanVideo")
public class KanbanVideoController extends BaseController{

    private final AuthCommonService authCommonService;

    @Autowired
    public void setAuthCommonService (AuthCommonService authCommonService) {
        this.authCommonService = authCommonService;
    }
}

但是这样写感觉相较于以前的方式多了很多的代码,看起来不够简洁,因此可以结合lombok的@RequiredArgsConstructor进行简化,简化后的代码如下:

@RestController
@RequestMapping("/kanbanVideo")
@RequiredArgsConstructor
public class KanbanVideoController extends BaseController{

    private final AuthCommonService authCommonService;
}