spring源码-ioc-bean和bean工厂后置处理器

620 阅读2分钟

不要问我阅读spring源码有什么用,问就是没有用,只是让我自己使用spring的过程中自信点!

相关文章

spring-相关文章

BeanPostProcessor

spring虽然给方法和类起的名都比较长,但是见名知意, bean 后置 处理器

看段代码

//要使用bean的后置处理器,需要把它交给spring-ioc管理
@Component
public class MyBeanPostProcessor implements BeanPostProcessor{

        //重写父类BeanPostProcessor 的方法
        //假如想现在这样写的话,spring启动的过程中控制台会打印很多的   bean的后置处理器执行了 
        //因为每个bean实例化之后都会调用这个方法,具体是在哪里调用的 我会在后续的 spring-ioc 的章节中说明
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("bean的后置处理器执行了");
		return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		// TODO Auto-generated method stub
		return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
	}
}

BeanPostProcessor

//我们需要使用自己定义的bean的后置处理器,实现这个接口,并重写其方法就行了
public interface BeanPostProcessor {
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
}

BeanFactoryPostProcessor

  1. bean工厂的后置处理器
  2. 不建议我们开发者使用
  3. 原理和BeanPostProcessor类似
  4. 顶层接口
@FunctionalInterface
public interface BeanFactoryPostProcessor {
	/**
	 * Modify the application context's internal bean factory after its standard
	 * initialization. All bean definitions will have been loaded, but no beans
	 * will have been instantiated yet. This allows for overriding or adding
	 * properties even to eager-initializing beans.
	 * @param beanFactory the bean factory used by the application context
	 * @throws org.springframework.beans.BeansException in case of errors
	 */
	void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

测试代码

@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("bean工厂的后置处理器执行了1");

	}

	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		System.out.println("bean工厂的后置处理器执行了2");

	}

}

这里说下BeanDefinitionRegistryPostProcessor就是实现了BeanFactoryPostProcessor

BeanDefinitionRegistryPostProcessor只是相当于对BeanFactoryPostProcessor又做了一个封装,多了一个抽象方法

之所以实现BeanDefinitionRegistryPostProcessor是因为ConfigurationClassPostProcessor就是试下了它.以后要讲ConfigurationClassPostProcessor,所以熟悉下.