spring-註解----ext

spring-註解----extjava

 

 

package com.zwj.ext;

public class Blue {
    
    public Blue(){
        System.out.println("blue...constructor");
    }
    
    public void init(){
        System.out.println("blue...init...");
    }
    
    public void detory(){
        System.out.println("blue...detory...");
    }
    
    

}
Blue
package com.zwj.ext;

import java.util.concurrent.Executor;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.SimpleApplicationEventMulticaster;


/**
 * 擴展原理:
 * BeanPostProcessor:bean後置處理器,bean建立對象初始化先後進行攔截工做的
 * 
 * 一、BeanFactoryPostProcessor:beanFactory的後置處理器;
 *         在BeanFactory標準初始化以後調用,來定製和修改BeanFactory的內容;
 *         全部的bean定義已經保存加載到beanFactory,可是bean的實例還未建立
 * 
 * 
 * BeanFactoryPostProcessor原理:
 * 1)、ioc容器建立對象
 * 2)、invokeBeanFactoryPostProcessors(beanFactory);
 *         如何找到全部的BeanFactoryPostProcessor並執行他們的方法;
 *             1)、直接在BeanFactory中找到全部類型是BeanFactoryPostProcessor的組件,並執行他們的方法
 *             2)、在初始化建立其餘組件前面執行
 * 
 * 二、BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor
 *         postProcessBeanDefinitionRegistry();
 *         在全部bean定義信息將要被加載,bean實例還未建立的;
 * 
 *         優先於BeanFactoryPostProcessor執行;
 *         利用BeanDefinitionRegistryPostProcessor給容器中再額外添加一些組件;
 * 
 *     原理:
 *         1)、ioc建立對象
 *         2)、refresh()-》invokeBeanFactoryPostProcessors(beanFactory);
 *         3)、從容器中獲取到全部的BeanDefinitionRegistryPostProcessor組件。
 *             一、依次觸發全部的postProcessBeanDefinitionRegistry()方法
 *             二、再來觸發postProcessBeanFactory()方法BeanFactoryPostProcessor;
 * 
 *         4)、再來從容器中找到BeanFactoryPostProcessor組件;而後依次觸發postProcessBeanFactory()方法
 *     
 * 三、ApplicationListener:監聽容器中發佈的事件。事件驅動模型開發;
 *       public interface ApplicationListener<E extends ApplicationEvent>
 *         監聽 ApplicationEvent 及其下面的子事件;
 * 
 *      步驟:
 *         1)、寫一個監聽器(ApplicationListener實現類)來監聽某個事件(ApplicationEvent及其子類)
 *             @EventListener;
 *             原理:使用EventListenerMethodProcessor處理器來解析方法上的@EventListener;
 * 
 *         2)、把監聽器加入到容器;
 *         3)、只要容器中有相關事件的發佈,咱們就能監聽到這個事件;
 *                 ContextRefreshedEvent:容器刷新完成(全部bean都徹底建立)會發布這個事件;
 *                 ContextClosedEvent:關閉容器會發布這個事件;
 *         4)、發佈一個事件:
 *                 applicationContext.publishEvent();
 *     
 *  原理:
 *      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);
 *          
 *   SmartInitializingSingleton 原理:->afterSingletonsInstantiated();
 *           1)、ioc容器建立對象並refresh();
 *           2)、finishBeanFactoryInitialization(beanFactory);初始化剩下的單實例bean;
 *               1)、先建立全部的單實例bean;getBean();
 *               2)、獲取全部建立好的單實例bean,判斷是不是SmartInitializingSingleton類型的;
 *                   若是是就調用afterSingletonsInstantiated();
 *         
 * 
 *
 */
@ComponentScan("com.zwj.ext")
@Configuration
public class ExtConfig {
    
    @Bean
    public Blue blue(){
        return new Blue();
    }

}
ExtConfig
package com.zwj.ext;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

//@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {

    //當容器中發佈此事件之後,方法觸發
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        // TODO Auto-generated method stub
        System.out.println("收到事件:"+event);
    }

}
MyApplicationListener
package com.zwj.ext;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;


//@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor{

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("MyBeanDefinitionRegistryPostProcessor...bean的數量:"+beanFactory.getBeanDefinitionCount());
    }

    //BeanDefinitionRegistry Bean定義信息的保存中心,之後BeanFactory就是按照BeanDefinitionRegistry裏面保存的每個bean定義信息建立bean實例;
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("postProcessBeanDefinitionRegistry...bean的數量:"+registry.getBeanDefinitionCount());
        //RootBeanDefinition beanDefinition = new RootBeanDefinition(Blue.class);
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Blue.class).getBeanDefinition();
        registry.registerBeanDefinition("hello", beanDefinition);
    }

}
MyBeanDefinitionRegistryPostProcessor
package com.zwj.ext;

import java.util.Arrays;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

//@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("MyBeanFactoryPostProcessor...postProcessBeanFactory...");
        int count = beanFactory.getBeanDefinitionCount();
        String[] names = beanFactory.getBeanDefinitionNames();
        System.out.println("當前BeanFactory中有"+count+" 個Bean");
        System.out.println(Arrays.asList(names));
    }

}
MyBeanFactoryPostProcessor
package com.zwj.ext;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @EventListener(classes={ApplicationEvent.class})
    public void listen(ApplicationEvent event){
        System.out.println("UserService。。監聽到的事件:"+event);
    }

}
UserService
package com.zwj.test;

import org.junit.Test;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.zwj.ext.ExtConfig;


public class IOCTest_Ext {
    
    @Test
    public void test01(){
        AnnotationConfigApplicationContext applicationContext  = new AnnotationConfigApplicationContext(ExtConfig.class);
        
        
        //發佈事件;
        applicationContext.publishEvent(new ApplicationEvent(new String("我發佈的時間")) {
        });
        
        applicationContext.close();
    }

}


/*
blue...constructor
UserService。。監聽到的事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@11028347: startup date [Sun Oct 28 13:24:35 CST 2018]; root of context hierarchy]
UserService。。監聽到的事件:com.zwj.test.IOCTest_Ext$1[source=我發佈的時間]
UserService。。監聽到的事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@11028347: startup date [Sun Oct 28 13:24:35 CST 2018]; root of context hierarchy]
*/
IOCTest_Ext
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zwj</groupId>
  <artifactId>spring-annotation---ext</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.inject/javax.inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>





    </dependencies>
</project>
pom.xml
相關文章
相關標籤/搜索