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

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

相关文章

spring-相关文章spring

BeanPostProcessor

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

看段代码ide

//要使用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);
	}
}
复制代码

BeanPostProcessorpost

//咱们须要使用本身定义的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就是实现了BeanFactoryPostProcessorspa

BeanDefinitionRegistryPostProcessor只是至关于对BeanFactoryPostProcessor又作了一个封装,多了一个抽象方法code

之因此实现BeanDefinitionRegistryPostProcessor是由于ConfigurationClassPostProcessor就是试下了它.之后要讲ConfigurationClassPostProcessor,因此熟悉下.接口

相关文章
相关标签/搜索