Bean的生命周期步骤

x33g5p2x  于2021-12-27 转载在 其他  
字(5.5k)|赞(0)|评价(0)|浏览(332)

一 Bean的创建生命周期

1 Bean 一定是对象,但对象不一定是 Bean。

2 Bean 的创建生命周期 

第一种形式:

UserService.class -----> 无参构造方法 -----> 普通对象 -----> 依赖注入 -----> 初始化前(@PostConstruct) -----> 初始化(InitializingBean) -----> Bean(代理对象成为 Bean)

第二种形式:

UserService.class -----> 无参构造方法 -----> 普通对象 -----> 依赖注入 -----> 初始化前(@PostConstruct) -----> 初始化(InitializingBean) -----> 初始化后(AOP) -----> 代理对象 -----> Bean(代理对象成为 Bean)

二 相关代码

1 实体类

package beandemo.entity;

public class User {
}

2 service 层

OrderService 类

package beandemo.service;

import org.springframework.stereotype.Component;

@Component
public class OrderService {
}

UserService 类

package beandemo.service;

import beandemo.entity.User;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class UserService implements InitializingBean {
    @Autowired
    private OrderService orderService;
    private User admin; // 从 mysql 中查出来的
    // 初始化前注解
    @PostConstruct
    public void initUser(){
        System.out.println("从数据库查出数据,然后初始化 admin");
    }
    public void test() {
        System.out.println("hello Spring");
    }
    // 初始化
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("这个方法也可以实现:从数据库查出数据,然后初始化 admin");
    }
}

3 配置类

package beandemo;

import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
}

4 测试类

package beandemo;

import beandemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) {
        // Spring FrameWork 只是 Spring 家族中的一个成员,Spring 一共有24个项目
        // context 就是一个构造 Bean 的工厂,或者理解为 Bean 容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        UserService userService = context.getBean("userService", UserService.class);
        userService.test();

        // 依赖注入的伪代码的实现
        for (Field field : userService.getClass().getFields()) {
            if (field.isAnnotationPresent(Autowired.class)) {
                try {
                    field.set(userService, "some Field Value");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        // AbstractAutowireCapableBeanFactory 这个类可以看一下 Bean 的生命周期过程
        // 初始化前的伪代码实现
        for (Method method : userService.getClass().getMethods()) {
            if (method.isAnnotationPresent(PostConstruct.class)) {
                try {
                    method.invoke(userService, "some parameters");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }

        // 初始化的伪代码实现
        /**
         * if(obj instanceof InitializingBean){
         *     ((InitializingBean)obj).afterPropertiesSet();
         * }
         */
    }
}

三 依赖注入的伪代码实现

for (Field field : userService.getClass().getFields()) {
    if(field.isAnnotationPresent(Autowired.class)){
        try {
            field.set(userService,?);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

四 初始化前的伪代码实现

for (Method method : userService.getClass().getMethods()) {
    if (method.isAnnotationPresent(PostConstruct.class)) {
        try {
            method.invoke(userService, "some parameters");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

五 初始化的伪代码实现

早期的 Spring 只有初始化,没有初始化前和初始化后。

if(obj instanceof InitializingBean){
    ((InitializingBean)obj).afterPropertiesSet();
}

六 Spring 源代码

// 创建 Bean 的源码
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
      throws BeanCreationException {
   // 实例化 Bean
   BeanWrapper instanceWrapper = null;
   if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
   }
   if (instanceWrapper == null) {
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }
   final Object bean = instanceWrapper.getWrappedInstance();
   Class<?> beanType = instanceWrapper.getWrappedClass();
   

   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
       // 依赖注入,填充属性
      populateBean(beanName, mbd, instanceWrapper);
      // 初始化
      exposedObject = initializeBean(beanName, exposedObject, mbd);
   }

)

// 初始化(初始化前、初始化、初始化后)源码
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
   if (System.getSecurityManager() != null) {
      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
         invokeAwareMethods(beanName, bean);
         return null;
      }, getAccessControlContext());
   }
   else {
      invokeAwareMethods(beanName, bean);
   }

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      // 初始化前
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
      // 初始化
      invokeInitMethods(beanName, wrappedBean, mbd);
   }
   catch (Throwable ex) {
      throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null),
            beanName, "Invocation of init method failed", ex);
   }
   if (mbd == null || !mbd.isSynthetic()) {
        // 初始化后
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }

   return wrappedBean;
}

// 初始化源码
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
      throws Throwable {
   // 判断 bean 是否实现了 InitializingBean 接口
   boolean isInitializingBean = (bean instanceof InitializingBean);
   if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
      if (logger.isTraceEnabled()) {
         logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
      }
      if (System.getSecurityManager() != null) {
         try {
            AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
               ((InitializingBean) bean).afterPropertiesSet();
               return null;
            }, getAccessControlContext());
         }
         catch (PrivilegedActionException pae) {
            throw pae.getException();
         }
      }
      else {
         // 强制调用初始化方法 afterPropertiesSet
         ((InitializingBean) bean).afterPropertiesSet();
      }
   }
}

相关文章