五:测试
我们来写一个测试类,验证一下上面的问题:
5.1:首先声明一个自定义的Bean
@Component
public class CustomBean {
public CustomBean(){
System.out.println("调用CustomBean空的构造方法");
}
}
5.2:声明一个Bean来实现BeanPostProcessor
package com.wyq.spring.bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import Java.beans.PropertyDescriptor;
/**
* @Author: wyq
* @Desc:
* @Date: 2019/9/1 15:36
**/
@Component
@Scope("singleton")
public class TestBean implements BeanPostProcessor, SmartInitializingSingleton, InstantiationAwareBeanPostProcessor, DisposableBean{
private static final String BEAN_NAME= "customBean";
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (BEAN_NAME.equals(beanName)) {
System.out.println("==>BeanPostProcessor.postProcessBeforeInitialization");
}
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (BEAN_NAME.equals(beanName)) {
System.out.println("==>BeanPostProcessor.postProcessAfterInitialization");
}
return null;
}
@Override
public void afterSingletonsInstantiated() {
System.out.println("==>SmartInitializingSingleton.afterSingletonsInstantiated");
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (BEAN_NAME.equals(beanName)) {
System.out.println("==>InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation");
}
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if (BEAN_NAME.equals(beanName)) {
System.out.println("==>InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation");
}
return false;
}
@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
System.out.println("==>InstantiationAwareBeanPostProcessor.postProcessPropertyValues");
return null;
}
@Override
public void destroy() throws Exception {
System.out.println("==>DisposableBean.destroy");
}
}
5.3:启动容器:
六:总结
本篇博客主要是介绍了Spring的一些实例化的过程,高屋建瓴的分析了一下spring的bean加载过程,没有详细展开某个细节分析。spring的内部源码非常复杂,每个接口的实现类都在5个以上,如果深入细节,恐怕不是一篇博客能讲清楚的。这篇博客的目的就是在阐述spring的基本脉络中心路线顺序,首先我们需要有一个总体的认识,然后再深入到细节就是轻而易举的了。这也是一种学习的方法论,通过本篇博客我希望能梳理清楚spring的基本流程,对spring有一个比较清晰的认识。并且学习到优秀开源框架的设计基本思想,还有就是进一步提升自己的阅读源码的能力。