百味皆苦 java后端开发攻城狮

spring注解驱动开发(扩展原理)

2019-05-16
百味皆苦

后置处理器

  • BeanPostProcessor:bean的后置处理器,bean创建对象初始化前后进行拦截工作的
  • BeanFactoryPostProcessor:BeanFactory的后置处理器,在BeanFactory的标准初始化之后调用 所有bean的定义已经保存加载到BeanFactory,但是bean的实例还未创建

手动实现

/**
 * 扩展原理:
 * BeanPostProcessor:bean的后置处理器,bean创建对象初始化前后进行拦截工作的
 *
 * BeanFactoryPostProcessor:BeanFactory的后置处理器,在BeanFactory的标准初始化之后调用
 * 所有bean的定义已经保存加载到BeanFactory,但是bean的实例还未创建
 */
@Configuration
@ComponentScan("com.ldc.ext")
public class ExtConfig {

    @Bean
    public Blue blue() {
        return new Blue();
    }

}

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("MyBeanFactoryPostProcessor...PostProcessorBeanFactory...");
        int count = beanFactory.getBeanDefinitionCount();
        String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        System.out.println("当前的BeanFactory中有"+count+"个Bean");
        Stream.of(beanDefinitionNames).forEach(System.out::println);
    }
}

    @Test
    public void test01() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class);
    }

MyBeanFactoryPostProcessor…PostProcessorBeanFactory…
当前的BeanFactory中有9个Bean
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
extConfig
myBeanFactoryPostProcessor
blue

我们可以看到MyBeanFactoryPostProcessor是在所有的bean创建之前执行的;

原理

  BeanFactoryPostProcessor原理:
  1)、ioc容器创建对象
  2)、invokeBeanFactoryPostProcessors(beanFactory);
  		如何找到所有的BeanFactoryPostProcessor并执行他们的方法;
  			1)、直接在BeanFactory中找到所有类型是BeanFactoryPostProcessor的组件,并执行他们的方法
  			2)、在初始化创建其他组件前面执行

自定义Bean

  2、BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor
  		postProcessBeanDefinitionRegistry();
  		在所有bean定义信息将要被加载,bean实例还未创建的;

  		优先于BeanFactoryPostProcessor执行;
  		利用BeanDefinitionRegistryPostProcessor给容器中再额外添加一些组件;

  	原理:
  		1)、ioc创建对象
  		2)、refresh()-》invokeBeanFactoryPostProcessors(beanFactory);
  		3)、从容器中获取到所有的BeanDefinitionRegistryPostProcessor组件。
  			1、依次触发所有的postProcessBeanDefinitionRegistry()方法
  			2、再来触发postProcessBeanFactory()方法BeanFactoryPostProcessor;

  		4)、再来从容器中找到BeanFactoryPostProcessor组件;然后依次触发postProcessBeanFactory()方法

手动实现

@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("MyBeanDefinitionRegistryPostProcessor...bean的数量"+beanFactory.getBeanDefinitionCount());
    }

    //BeanDefinitionRegistry是bean定义信息的保存中心,以后BeanFactory就是按照BeanDefinitionRegistry里面保存的每一个bean的定义信息创建bean的实例
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("MyBeanDefinitionRegistryPostProcessor...bean的数量"+registry.getBeanDefinitionCount());
        RootBeanDefinition beanDefinition = new RootBeanDefinition(Blue.class);
        registry.registerBeanDefinition("hello",beanDefinition);
    }
}

MyBeanDefinitionRegistryPostProcessor…bean的数量10
MyBeanDefinitionRegistryPostProcessor…bean的数量11
MyBeanFactoryPostProcessor…PostProcessorBeanFactory…
当前的BeanFactory中有11个Bean
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
extConfig
myBeanDefinitionRegistryPostProcessor
myBeanFactoryPostProcessor
blue
hello

应用监听器

 3、ApplicationListener:监听容器中发布的事件。事件驱动模型开发;
  	  public interface ApplicationListener<E extends ApplicationEvent>
  		监听 ApplicationEvent 及其下面的子事件;

  	 步骤:
  		1)、写一个监听器(ApplicationListener实现类)来监听某个事件(ApplicationEvent及其子类)
  			@EventListener;
  			原理:使用EventListenerMethodProcessor处理器来解析方法上的@EventListener;

  		2)、把监听器加入到容器;
  		3)、只要容器中有相关事件的发布,我们就能监听到这个事件;
  				ContextRefreshedEvent:容器刷新完成(所有bean都完全创建)会发布这个事件;
  				ContextClosedEvent:关闭容器会发布这个事件;
  		4)、发布一个事件:
  				applicationContext.publishEvent();

手动实现

@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
    //当容器中发布次事件,方法触发
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("收到的事件"+event);
    }
}

    @Test
    public void test01() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class);
        applicationContext.close();
    }

MyBeanDefinitionRegistryPostProcessor…bean的数量11
MyBeanDefinitionRegistryPostProcessor…bean的数量12
MyBeanFactoryPostProcessor…PostProcessorBeanFactory…
当前的BeanFactory中有12个Bean
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
extConfig
myApplicationListener
myBeanDefinitionRegistryPostProcessor
myBeanFactoryPostProcessor
blue
hello
收到的事件org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@3a4afd8d: startup date [Wed Jan 16 20:51:59 CST 2019]; root of context hierarchy]
收到的事件org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@3a4afd8d: startup date [Wed Jan 16 20:51:59 CST 2019]; root of context hierarchy]

原理

   原理:
   	ContextRefreshedEvent、IOCTest_Ext$1[source=我发布的时间]、ContextClosedEvent;
   1)、ContextRefreshedEvent事件:
   	1)、容器创建对象:refresh();
   	2)、finishRefresh();容器刷新完成会发布ContextRefreshedEvent事件
   2)、自己发布事件;
   3)、容器关闭会发布ContextClosedEvent;

   【事件发布流程】:
   	3)、publishEvent(new ContextRefreshedEvent(this));
   			1)、获取事件的多播器(派发器):getApplicationEventMulticaster()
   			2)、multicastEvent派发事件:
   			3)、获取到所有的ApplicationListener;
   				for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
   				1)、如果有Executor,可以支持使用Executor进行异步派发;
   					Executor executor = getTaskExecutor();
   				2)、否则,同步的方式直接执行listener方法;invokeListener(listener, event);
   				 拿到listener回调onApplicationEvent方法;

   【事件多播器(派发器)】
   	1)、容器创建对象:refresh();
   	2)、initApplicationEventMulticaster();初始化ApplicationEventMulticaster;
   		1)、先去容器中找有没有id=“applicationEventMulticaster”的组件;
   		2)、如果没有this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
   			并且加入到容器中,我们就可以在其他组件要派发事件,自动注入这个applicationEventMulticaster;

   【容器中有哪些监听器】
   	1)、容器创建对象:refresh();
   	2)、registerListeners();
   		从容器中拿到所有的监听器,把他们注册到applicationEventMulticaster中;
   		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
   		//将listener注册到ApplicationEventMulticaster中
   		getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);

@EventListener

@Service
public class UserService {
    @EventListener(classes = {ApplicationEvent.class})
    public void listen(ApplicationEvent event) {
        System.out.println("UserService监听的事件"+event);
    }
}

UserService监听的事件org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@3a4afd8d: startup date [Wed Jan 16 21:11:12 CST 2019]; root of context hierarchy]
收到的事件org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@3a4afd8d: startup date [Wed Jan 16 21:11:12 CST 2019]; root of context hierarchy]

    SmartInitializingSingleton 原理:->afterSingletonsInstantiated();
    		1)、ioc容器创建对象并refresh();
    		2)、finishBeanFactoryInitialization(beanFactory);初始化剩下的单实例bean;
    			1)、先创建所有的单实例bean;getBean();
    			2)、获取所有创建好的单实例bean,判断是否是SmartInitializingSingleton类型的;
    				如果是就调用afterSingletonsInstantiated();


Similar Posts

Comments