Spring Bean的生命周期理解

 

 

《Spring in action》 

 

 

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class MyBean implements BeanNameAware,BeanFactoryAware,ApplicationContextAware,InitializingBean,BeanPostProcessor,DisposableBean {
    
    ApplicationContext applicationContext;
    BeanFactory beanFactory;
    String beanname;
    String properties;
    public MyBean(){
        System.out.println("MyBean 被创建了");
    }
    @Override
    public void setBeanName(String name) {
        System.out.println("BeanNameAware的setBeanName:"+name);
        beanname=name;
    }
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("BeanFactoryAware的setbeanFactory:"+beanFactory);
        this.beanFactory=beanFactory;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("ApplicationContextAware的setApplicationContext:"+applicationContext);
        this.applicationContext=applicationContext;
    }
    //实现BeanPostProcessor的方法会被容器自动调用;
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(beanName+"开始实例化!");
        return bean;//对bean处理后放回容器,如果return null 容器将没有bean;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        properties="sdfsf";
        System.out.println("InitializingBean的afterPropertiesSet!");
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(beanName+"实例化完成!");
        return bean;
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("Bean销毁——destroy:"+this.toString());
    }
}

 

posted @ 2019-05-03 23:30  笔记Next  阅读(181)  评论(0编辑  收藏  举报