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,因此熟悉下.接口

相關文章
相關標籤/搜索