Spring 一些重要的接口、类

Spring Bean生命周期


Spring Bean生命周期

ApplicationContextAware 接口

1、作用: 用于帮助获取 Spring 的上下文
2、当 Bean 实现了 ApplicationContextAware 接口,setApplicationContext() 在 Bean 初始化结束后被调用

BeanNameAware

1、作用:用于获取该在 Spring 容器中的名称
2、setBeanName(String name) 方法在 Bean 初始化后被调用

ApplicationListener

1、作用:Spring 时间机制用于监听异步广播事件 ApplicationEvent 事件
2、任何 ApplicationListener 接口的类 onAppEvent() 会收到 ApplicationEvent 事件。Dubbo ServiceBean 就实现了此接口 finishRefresh() 中会发送 ContextRefreshedEvent 事件用于触发服务发布。

InitializingBean

1、作用: afterPropertiesSet() Bean 中属性设置完后,也就是 IOC,依赖注入完后被调用
2、afterPropertiesSet() 跟 initMethod 方法类似,initMethod采用反射方式被调用
2、Mybatis 的 MapperScannerConfigurer 类就实现了此接口

DisposableBean

1、作用: destroy(),方法在 Bean 被销毁后被调用
2、与 destroy-method() 方法类似

BeanDefinitionRegistryPostProcessor

1、作用: 用于动态注册 Bean ,即类没有被纳入 Spring 容器管理。BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor
2、可以自定义的注册bean定义的逻辑

public class CustomBeanDefinitionRegistry implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        RootBeanDefinition helloBean = new RootBeanDefinition(Hello.class);
        //新增Bean定义
        registry.registerBeanDefinition("hello", helloBean);
    }

}

FactoryBean

1、作用:实例工厂定义一种类型并创建一个实例交给 Spring 容器管理

    public interface FactoryBean {  
       
       /** 
        * 获取实际要返回的bean对象。 
        * @return 
        * @throws Exception 
        */  
       T getObject() throws Exception;  
       
       /** 
        * 获取返回的对象类型 
        * @return 
        */  
       Class getObjectType();  
       
       /** 
        * 是否单例 
        * @return 
        */  
       boolean isSingleton();  
       
    }  

BeanPostProcessor

1、作用:在 Spring 容器完成 Bean 的实例化、配置和其他的初始化前后添加一些自己的逻辑处理

public class MyBeanPostProcessor implements BeanPostProcessor {  
   
     public MyBeanPostProcessor() {  
        super();  
        System.out.println("这是BeanPostProcessor实现类构造器!!");          
     }  
   
     @Override  
     public Object postProcessAfterInitialization(Object bean, String arg1)  
             throws BeansException {  
         System.out.println("bean处理器:bean创建之后..");  
         return bean;  
     }  
   
     @Override  
     public Object postProcessBeforeInitialization(Object bean, String arg1)  
             throws BeansException {  
         System.out.println("bean处理器:bean创建之前..");  
       
         return bean;  
     }  
 }  

BeanFactoryPostProcessor

1、作用: 对应 BeanFactory 加载完bean的定义后回调 postProcessBeanFactory()

public interface BeanFactoryPostProcessor {

    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

BeanDefinition

1、作用:用于装载 配置文件 xml 内容

更详细的过程

dubbo 服务发布流程

dubbo 服务发布流程

你可能感兴趣的:(Spring 一些重要的接口、类)