【源码分析】Spring依赖注入原理

深藏阁楼爱情的钟 2023-10-04 19:27 136阅读 0赞

文章目录

  • 一、三种依赖注入方式
    • 字段注入
    • 构造器注入
    • Setter注入
  • 二、依赖注入原理
    • Bean 注册
    • Bean 实例化

一、三种依赖注入方式

在Spring中提供了三种实现依赖注入的方式:字段注入、构造器注入、Setter方法注入

首先我们先创建一个Service层的接口以及对应的实现类,基于以下实现类来实现依赖注入的方式:

  1. public interface UserService {
  2. public void UserInfo();
  3. }
  4. public class UserServiceImpl implements UserService{
  5. @Override
  6. public void UserInfo() {
  7. System.out.println("UserInfo to do ...");
  8. }
  9. }

字段注入

Spring中通过@Autowired注解,可以完成注入。

  1. public class ClientService {
  2. @Autowired
  3. private UserService userService;
  4. public void UserInfo(){
  5. userService.UserInfo();
  6. }
  7. }

字段注入是三种注入方式最简单、最常用的一种方式,但是也是最需要避免使用的一种方式。那为什么要避免使用呢?接下来进行分析一下。

ClientService 类中,我们定义了一个私有化的变量userService来注入该接口的实例,但是这个实例只能在ClientService 类中访问到,脱离容器环境无法访问到。

  1. ClientService clientService = new ClientService();
  2. clientService.UserInfo();

在这里插入图片描述

如上图执行结果抛出NullPointerException空指针异常,原因很简单无法在ClientService 类的外部实例化UserService 对象。采用字段注入的话,类与容器的耦合度较高,无法脱离容器使用目标对象。这就得出了避免使用字段注入的第一个原因:对象的外部可见性较差

避免使用字段注入第二个原因:可能导致潜在的循环依赖。循环依赖指的是两个类之间互相进行注入。代码如下

  1. public class ClassA {
  2. @Autowired
  3. private ClassB classB;
  4. }
  5. public class ClassB {
  6. @Autowired
  7. private ClassA classA;
  8. }

如上代码显然,ClassA和ClassB发生循环依赖。在Spring启动的时候不会发生错误,但是在使用具体的某个类时会报错。

构造器注入

构造器注入就是使用类的构造函数来完成对象的注入。

  1. public class ClientService {
  2. private UserService userService;
  3. @Autowired
  4. public ClientService(UserService userService) {
  5. this.userService = userService;
  6. }
  7. public void UserInfo(){
  8. userService.UserInfo();
  9. }
  10. }

通过构造器注入可以解决对象的外部可见性的问题,因为userService是通过ClientService 构造函数进行注入的。基于构造器注入,回顾一下之前循环依赖的问题。代码如下

  1. public class ClassA {
  2. private ClassB classB;
  3. @Autowired
  4. public ClassA(ClassB classB) {
  5. this.classB = classB;
  6. }
  7. }
  8. public class ClassB {
  9. private ClassA classA;
  10. @Autowired
  11. public ClassB(ClassA classA) {
  12. this.classA = classA;
  13. }
  14. }

在Spring项目启动的时候,会抛出循环依赖异常,可以提醒开发者避免使用循环依赖。但是构造器注入也是有问题的,当构造函数中存在较多的依赖对象时,大量的构造函数参数回访代码出现冗余。接下来就引入Setter方法注入

Setter注入

Setter方法注入代码如下

  1. public class ClientService {
  2. private UserService userService;
  3. @Autowired
  4. public void setUserService(UserService userService) {
  5. this.userService = userService;
  6. }
  7. public void UserInfo(){
  8. userService.UserInfo();
  9. }
  10. }

Setter注入相比于构造器注入可读性更强,可以将多个实例对象通过多个Setter方法逐一进行注入。回顾之前的循环依赖问题。代码如下

  1. public class ClassA {
  2. private ClassB classB;
  3. @Autowired
  4. public void setClassB(ClassB classB) {
  5. this.classB = classB;
  6. }
  7. }
  8. public class ClassB {
  9. private ClassA classA;
  10. @Autowired
  11. public void setClassA(ClassA classA) {
  12. this.classA = classA;
  13. }
  14. }

在ClassA 和ClassB 作用域都为单例bean的前提下,代码正常执行。

总结:Setter适合可选对象的注入;构造方法适合强制对象的注入;字段注入避免使用。

二、依赖注入原理

前面介绍完依赖注入的三种实现方式,接下来结合Spring源码深入的了解下依赖注入的原理,通过Bean 注册和Bean 实例化两个模块进行阐述。

Bean 注册

在Spring中我们往往通过一个应用的上下文(ApplicationContext)对象来操作各种Bean。

  1. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

xxxApplicationContext接口在Spring中就代表一个Spring IOC 容器,Spring中存在大量的ApplicationContext接口的实现类。如果基于注解的配置方式,就使用AnnotationConfigApplicationContext 来初始化上下文容器对象。接下来进入AnnotationConfigApplicationContext的源码,查看其构造函数如下:

  1. /**
  2. * Create a new AnnotationConfigApplicationContext, deriving bean definitions
  3. * from the given component classes and automatically refreshing the context.
  4. * @param componentClasses one or more component classes — for example,
  5. * {@link Configuration @Configuration} classes
  6. */
  7. public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
  8. this();
  9. // 根据注解配置类注册Bean
  10. register(componentClasses);
  11. // 刷新容器
  12. refresh();
  13. }
  14. /**
  15. * Create a new AnnotationConfigApplicationContext, scanning for components
  16. * in the given packages, registering bean definitions for those components,
  17. * and automatically refreshing the context.
  18. * @param basePackages the packages to scan for component classes
  19. */
  20. public AnnotationConfigApplicationContext(String... basePackages) {
  21. this();
  22. // 根据包路径扫描Bean
  23. scan(basePackages);
  24. // 刷新容器
  25. refresh();
  26. }

通过以上两个构造函数可以看出,一个是根据注解配置类注册Bean,另一个通过包路径扫描Bean。点击进入register方法:

  1. //---------------------------------------------------------------------
  2. // 注解ConfigRegistry的实现
  3. // Implementation of AnnotationConfigRegistry
  4. //---------------------------------------------------------------------
  5. /**
  6. * Register one or more component classes to be processed.
  7. * <p>Note that {@link #refresh()} must be called in order for the context
  8. * to fully process the new classes.
  9. * @param componentClasses one or more component classes — for example,
  10. * {@link Configuration @Configuration} classes
  11. * @see #scan(String...)
  12. * @see #refresh()
  13. */
  14. @Override
  15. public void register(Class<?>... componentClasses) {
  16. Assert.notEmpty(componentClasses, "At least one component class must be specified");
  17. this.reader.register(componentClasses);
  18. }

通过this.reader.register(componentClasses);可以看出,调用当前对象reader里面的register方法,而reader实际上是AnnotatedBeanDefinitionReader工具类来完成Bean的注册。继续点进register方法:

  1. /**
  2. * Register one or more component classes to be processed.
  3. * <p>Calls to {@code register} are idempotent; adding the same
  4. * component class more than once has no additional effect.
  5. * @param componentClasses one or more component classes,
  6. * e.g. {@link Configuration @Configuration} classes
  7. */
  8. public void register(Class<?>... componentClasses) {
  9. for (Class<?> componentClass : componentClasses) {
  10. registerBean(componentClass);
  11. }
  12. }
  13. /**
  14. * Register a bean from the given bean class, deriving its metadata from
  15. * class-declared annotations.
  16. * @param beanClass the class of the bean
  17. */
  18. public void registerBean(Class<?> beanClass) {
  19. doRegisterBean(beanClass, null, null, null, null);
  20. }

AnnotatedBeanDefinitionReader会遍历所有的componentClasses组件类,通过registerBean方法中的doRegisterBean方法完成Bean的注册。进入doRegisterBean

  1. /**
  2. * Register a bean from the given bean class, deriving its metadata from
  3. * class-declared annotations.
  4. * @param beanClass the class of the bean
  5. * @param name an explicit name for the bean
  6. * @param supplier a callback for creating an instance of the bean
  7. * (may be {@code null})
  8. * @param qualifiers specific qualifier annotations to consider, if any,
  9. * in addition to qualifiers at the bean class level
  10. * @param customizers one or more callbacks for customizing the factory's
  11. * {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
  12. * @since 5.0
  13. */
  14. private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
  15. @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
  16. @Nullable BeanDefinitionCustomizer[] customizers) {
  17. // 将注解配置类信息转换成一种 BeanDefinition
  18. AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
  19. if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
  20. return;
  21. }
  22. abd.setInstanceSupplier(supplier);
  23. // 获取bean的作用域元数据
  24. ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
  25. // 将bean的作用域写回 BeanDefinition
  26. abd.setScope(scopeMetadata.getScopeName());
  27. // 生成 beanName
  28. String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
  29. // 解析AnnotatedGenericBeanDefinition 中的 @lazy 和 @Primary注解
  30. AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
  31. // 处理@Qualifier 注解
  32. if (qualifiers != null) {
  33. for (Class<? extends Annotation> qualifier : qualifiers) {
  34. if (Primary.class == qualifier) {
  35. // 如果设置了@Primary注解,设置当前bean为首选bean
  36. abd.setPrimary(true);
  37. }
  38. else if (Lazy.class == qualifier) {
  39. // 如果设置了@lazy注解,则设置当前bean为延迟加载模式
  40. abd.setLazyInit(true);
  41. }
  42. else {
  43. abd.addQualifier(new AutowireCandidateQualifier(qualifier));
  44. }
  45. }
  46. }
  47. if (customizers != null) {
  48. for (BeanDefinitionCustomizer customizer : customizers) {
  49. customizer.customize(abd);
  50. }
  51. }
  52. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
  53. definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  54. // 注册 bean对象
  55. BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
  56. }

总的来看:

① 首先需要构造描述bean实例化信息的BeanDefinition对象,需要将注解配置类信息转化为AnnotatedGenericBeanDefinition 类型,此处的AnnotatedGenericBeanDefinition 就是一种BeanDefinition类型,包含了Bean的构造函数参数,属性值以及添加的注解信息。
② 设置BeanDefinition属性,完成对@Scope、@Lazy、@Primary等注解的处理
③ 最后通过registerBeanDefinition()方法完成Bean的注册。

Bean 实例化

现在Spring IOC容器对Bean的创建过程并没有完成,目前只是将Bean的定义加载到了容器中,但是可能容器本身已经存在这些Bean的定义,所以需要使用refresh()方法刷新容器,回到最开始进入AnnotationConfigApplicationContext的源码,查看其构造函数如下:

  1. /**
  2. * Create a new AnnotationConfigApplicationContext, deriving bean definitions
  3. * from the given component classes and automatically refreshing the context.
  4. * @param componentClasses one or more component classes — for example,
  5. * {@link Configuration @Configuration} classes
  6. */
  7. public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
  8. this();
  9. // 根据注解配置类注册Bean
  10. register(componentClasses);
  11. // 刷新容器
  12. refresh();
  13. }

接下来分析refresh方法,点击进入:

  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized (this.startupShutdownMonitor) {
  4. ...
  5. // 提取配置信息,注册到BeanFactory中
  6. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  7. ...
  8. try {
  9. ......
  10. // 初始化所有的单例 bean
  11. finishBeanFactoryInitialization(beanFactory);
  12. // Last step: publish corresponding event.
  13. finishRefresh();
  14. }
  15. catch (BeansException ex) {
  16. ......
  17. }
  18. finally {
  19. ......
  20. }
  21. }
  22. }

可以看出obtainFreshBeanFactory完成对Bean的注册返回一个BeanFactory。而finishBeanFactoryInitialization方法真正完成Bean实例化的入口。真正完成实例化的方法为DefaultListableBeanFactory类中的preInstantiateSingletons方法,进入此方法:

  1. @Override
  2. public void preInstantiateSingletons() throws BeansException {
  3. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
  4. // 触发所有非懒加载的单例Bean的初始化操作
  5. for (String beanName : beanNames) {
  6. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  7. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  8. if (isFactoryBean(beanName)) {
  9. ......
  10. }
  11. else {
  12. // 获取Bean
  13. getBean(beanName);
  14. }
  15. }
  16. }
  17. ......
  18. }

进入到getBean()方法:

  1. //---------------------------------------------------------------------
  2. // Implementation of BeanFactory interface
  3. //---------------------------------------------------------------------
  4. @Override
  5. public Object getBean(String name) throws BeansException {
  6. return doGetBean(name, null, null, false);
  7. }

Bean的初始化过程就在这个方法中。在当前的抽象类AbstractBeanFactory中有一个抽象方法createBean如下:

  1. protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  2. throws BeanCreationException;

在Spring中实现这个抽象方法的唯一BeanFactory是AbstractAutowireCapableBeanFactory,真正完成Bean创建是在doCreateBean:

  1. /**
  2. * 此类的中心方法:创建一个bean实例,
  3. * Central method of this class: creates a bean instance,
  4. * populates the bean instance, applies post-processors, etc.
  5. * @see #doCreateBean
  6. */
  7. @Override
  8. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  9. throws BeanCreationException {
  10. ......
  11. try {
  12. // 真正创建Bean
  13. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  14. if (logger.isTraceEnabled()) {
  15. logger.trace("Finished creating instance of bean '" + beanName + "'");
  16. }
  17. return beanInstance;
  18. }
  19. catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
  20. // A previously detected exception with proper bean creation context already,
  21. // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
  22. throw ex;
  23. }
  24. catch (Throwable ex) {
  25. throw new BeanCreationException(
  26. mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
  27. }
  28. }

最后进入到doCreateBean如下:

  1. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
  2. throws BeanCreationException {
  3. ......
  4. // 初始化一个bean
  5. if (instanceWrapper == null) {
  6. instanceWrapper = createBeanInstance(beanName, mbd, args);
  7. }
  8. ......
  9. Object exposedObject = bean;
  10. try {
  11. // 初始化Bean实例
  12. populateBean(beanName, mbd, instanceWrapper);
  13. // 执行初始化bean实例回调
  14. exposedObject = initializeBean(beanName, exposedObject, mbd);
  15. }
  16. catch (Throwable ex) {
  17. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  18. throw (BeanCreationException) ex;
  19. }
  20. else {
  21. throw new BeanCreationException(
  22. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  23. }
  24. }
  25. ......
  26. // 将bean注册为一次性。
  27. try {
  28. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  29. }
  30. catch (BeanDefinitionValidationException ex) {
  31. throw new BeanCreationException(
  32. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  33. }
  34. return exposedObject;
  35. }

总的来看:

createBeanInstance方法用于根据配置生成具体的Bean,最终通过反射方法实现,执行完后Bean已经被创建,但是不完整,没有属性的注入。
populateBean方法用于实现属性的自动注入,包含byName、byType、@Autowired、@Value属性的设置,执行完之后Bean就是完整的。
initializeBean方法是一种扩展性的机制,用于Bean初始化完成后的一些定制化操作。

至此分析Spring中Bean依赖注入的过程就全部结束,希望对大家有所帮助!!!
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读