【Spring的Bean的生命周期】

目录

1.实例化Bean对象

Bean的实例化是在BeanFactory中完成的。BeanFactory通过调用Bean的构造函数来创建Bean的实例,此时还未进行任何属性注入。
源码:

//从beanDefinition中获取Bean的class
Class<?> beanClass = resolveBeanClass(beanDefinition, beanName);
//根据构造函数实例化Bean对象
Object beanInstance = createBeanInstance(beanName, beanDefinition, args);

实例代码:

 // 使用容器
@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }

}

没有整合SpringBoot之前:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//读取配置文件并实例化Bean
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Object bean = context.getBean("beanId");

2.处理Bean的属性依赖

在实例化Bean对象之后,Spring容器会将按照实例化时配置的属性进行依赖注入,也就是将其他的Bean对象注入进来,这一步也是整个生命周期中比较重要的一步。

populateBean(beanName, beanDefinition, instanceWrapper);

例如:

@Component("userService")
public class UserServiceImpl implements BeanNameAware, UserService {

    @Autowied
    private OrderService orderService;
}

UserServiceImpl 需要依赖OrderService ,因此在UserServiceImpl 实例化之后,Spring容器会自动将OrderService 对象注入进来。
源码:

3.Bean的初始化

初始化是在BeanFactory中完成的,包括调用InitializingBeanafterPropertiesSet()方法或@PostConstruct注解标注的方法等。

if (mbd.getInitMethodName() != null || mbd.getDestroyMethodName() != null) {
    return createLifecycleProcessor().initializeBean(beanName, exposedObject, mbd);
}

3.1 前置处理

如果Bean实现了BeanPostProcessor接口,则在Bean的初始化之前调用postProcessBeforeInitialization()方法。这是BeanPostProcessor的前置处理,可以对Bean进行任何必要的修改。

3.2 后置处理

如果Bean实现了BeanPostProcessor接口,则在Bean的初始化之后调用postProcessAfterInitialization()方法。这是BeanPostProcessor的后置处理,可以对Bean进行任何必要的修改。

4.Bean在容器中的使用

Bean在容器中的使用包括:getBean@Autowire注解等。当容器使用某个Bean时,Bean实例已经存在并且初始化完毕。

5.Bean的销毁

Bean的销毁可以通过实现DisposableBean接口的其中一个方法destroy()实现,也可以通过@PreDestroy注解标注的方法实现。由于Spring的IoC容器是单例模式的,所以在容器的销毁过程中会调用单例Bean的销毁方法。

源码:

if (mbd.getDestroyMethodName() != null) {
    registerDisposableBeanIfNecessary(beanName, bean, mbd);
}

小结:

较为重要的在2、3步。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值