大公司为什么禁止在 Spring Boot 项目中使用 @Autowired 注解?
1、说明
最近公司升级框架,由原来的spring framerwork 3.0
升级到5.0
,然后写代码的时候突然发现idea在属性注入的 @Autowired 注解上给出警告提示,就像下面这样的,也挺懵逼的,毕竟这么写也很多年了。
Field injection is not recommended
查阅了相关文档了解了一下,原来这个提示是spring framerwork 4.0
以后开始出现的,spring 4.0开始就不推荐使用属性注入,改为推荐构造器注入和setter注入。
下面将展示了spring框架可以使用的不同类型的依赖注入,以及每种依赖注入的适用情况。
2、依赖注入的类型
尽管针对spring framerwork 5.1.3
的文档只定义了两种主要的依赖注入类型,但实际上有三种;
- 基于构造函数的依赖注入
- 基于setter的依赖注入
- 基于字段的依赖注入
其中基于字段的依赖注入
被广泛使用,但是idea或者其他静态代码分析工具会给出提示信息,不推荐使用。
甚至可以在一些Spring官方指南中看到这种注入方法:
2.1 基于构造函数的依赖注入
在基于构造函数的依赖注入中,类构造函数被标注为 @Autowired,并包含了许多与要注入的对象相关的参数。
@Component public class ConstructorBasedInjection { private final InjectedBean injectedBean; @Autowired public ConstructorBasedInjection(InjectedBean injectedBean) { this.injectedBean = injectedBean; } }登录后复制
public class SimpleMovieLister { // the SimpleMovieLister has a dependency on a MovieFinder private MovieFinder movieFinder; // a constructor so that the Spring container can inject a MovieFinder public SimpleMovieLister(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // business logic that actually uses the injected MovieFinder is omitted... }登录后复制
2.2 基于Setter的依赖注入
在基于setter的依赖注入中,setter方法被标注为 @Autowired。一旦使用无参数构造函数或无参数静态工厂方法实例化Bean,为了注入Bean的依赖项,Spring容器将调用这些setter方法。
@Component public class SetterBasedInjection { private InjectedBean injectedBean; @Autowired public void setInjectedBean(InjectedBean injectedBean) { this.injectedBean = injectedBean; } }登录后复制
public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder; // a setter method so that the Spring container can inject a MovieFinder public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // business logic that actually uses the injected MovieFinder is omitted... }登录后复制