Spring(一) bean

转载:https://blog.csdn.net/a327369238/article/details/52193822(推荐)

       http://www.cnblogs.com/kenshinobiy/p/4652008.html

一 bean生命周期

 

Bean具体生命周期

1.postProcessBeanFactory(ConfigurableListableBeanFactory c)
    工厂后处理器(这名字其实只是一个翻译,感觉意义有的时候不一定正确),这个方法其实和Bean生命周期没多少关系,是IoC容器(ApplicationContext)初始化的一部分,详细的可以参考IoC容器初始化一节。具体是容器每一次刷新时(初始化)调用,它是对BeanDefinition进行后处理(BeanDefinition可以参考: Spring IoC容器结构),具体的作用就是可以修改配置文件的各个bean的配置。
    实现:写一个类,实现BeanFactoryPostProcessor接口,重写该方法,并在Spring配置文件中配置该类的一个bean 2.postProcessBeforeInstantiation(Class<?>c,String beanName)
    所有bean对象(注1)实例化之前执行,具体点就是执行每个bean类构造函数之前。
    实现:写一个类,实现InstantiationAwareBeanPostProcessor接口,重写该方法,在Spring配置文件中配置该类的一个bean。返回一个Object,但是实际上你返回一个null即可。
3.bean实例化,调用bean类构造函数
4.postProcessAfterInstantiation(Object bean,String beanName)
    bean类实例化之后,初始化之前调用
    实现:同第2步,重写该方法,但注意,返回类型这里是boolean,默认是false,你需要更改为true,否则无法注入属性
5.postProcessPropertyValue(属性名太长,详细查看代码实现)
    属性注入之前调用
    实现:同第2步,重写该方法,注意返回类型是PropertyValue,默认返回null,这里需改为返回第一个参数,详见代码章节3。
6. setBeanName(String beanName)
    属性注入后调用,该方法作用是让bean类知道自己所在的Bean的name或id属性。
    实现:bean类实现BeanNameAware接口,重写该方法。
7.setBeanFactory(BeanFactory factory)
    setBeanName后调用,该方法作用是让bean类知道自己所在的BeanFactory的属性(传入bean所在BeanFactory类型参数)。
    实现:bean类实现BeanFactoryAware接口,实现该方法。
8. postProcessBeforeInitialization(Object bean,String beanName)
    BeanPostProcessor作用是对bean实例化、初始化做些预处理操作(注2)。
    实现:写一个类,实现BeanPostProcessor接口,注意返回类型为Object,默认返回null,需要返回参数中bean。
9.postProcessBeforeInitialization(Object bean,Strign beanName)
    实现:同第2步,实现该方法,注意点同第8步。(注3)
10. afterPropertiesSet()
    实现:bean类实现InitializingBean接口,重写该方法。初始化工作,但实现该接口这种方法和Spring耦合,不推荐(这一点DisposableBean一样)。
11. xml_init()
    实现:spring bean配置文件中配置bean属性init-method=”xml_init”,这个方法名开发者自己定义,与Spring代码解耦。另外需要注意的是,init-method指定的方法不能有参数,有参数抛异常(这一点destroy-method一样)。
12. postProcessAfterInitialization(Object bean,Strign beanName)
    实现:同第8步,注意点相同。
13 postProcessAfterInitialization(Object bean,Strign beanName)
    实现:同第2步,注意点同第9步。
    程序执行,bean工作
14destroy()
    bean销毁前执行
    实现:bean类实现DisposableBean接口
15xml_destroy()
    实现:spring bean配置文件中配置bean属性destroy-method=”xml_destroy”,这个方法名开发者自己定义。

注1:这里的bean类指的是普通bean类,不包括这里实现了各类接口(就是2.2提到的这些接口)而在配置文件中声明的bean。
注2:如果有多个BeanPostProcessor实现类,其执行顺序参考:BeanPostProcessor详解。
注3:InstantiationAwareBeanPostProcessor接口继承自BeanPostProcessor接口,是它的子接口,扩展了两个方法,即bean实例化前后操作,当然前者也会有bean初始化前后操作,当它们两同时存在的话,开发者又同时对两者的postProcessBeforeInitialization、postProcessAfterInitialization方法实现了,先回去执行BeanPostProcessor的方法,再去执行InstantiationAwareBeanPostProcessor的。

代码实现;

bean类

public class HelloWorld implements BeanNameAware,BeanFactoryAware,InitializingBean,DisposableBean{

    private String message;

    public HelloWorld(){
        System.out.println("3.HelloWorld struct.......");
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void xml_init(){
        //xml开头的表示配置文件配置,这里是bean配置中init-method配置调用
        System.out.println("11.HelloWorld 初始化(init-method)");
    }

    public void xml_destroy(){
        //destroy-method 配置调用
        System.out.println("16.HelloWorld 销毁(destroy-method)");
    }


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        //setBeanName 后调用
        System.out.println("7.setBeanFactory(BeanFactory) setBeanName后调用");
    }

    @Override
    public void setBeanName(String s) {
      //属性注入后调用
        System.out.println("6.setBeanName(BeanNameAware) 属性注入后调用, 此时s = " + s);
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("15.destroy(DisposableBean) 在processAfterInitialization之后,配置的xml_destroy之前调用");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //processBeforeInitialization(BeanPostProcessor)后调用
        System.out.println("10.afterPropertiesSet(InitializingBean) processBeforeInitialization之后,配置的xml_init之前调用");

    }
}

BeanPostProcessor类

public class BeanPostProcessorTest implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("8.postProcessBeforeInitialization(BeanPostProcessor), bean = " + o.getClass());
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("12.postProcessAfterInitialization(BeanPostProcessor), bean = " + o.getClass());
        return o;
    }
}

BeanFactoryPostProcessor类

public class BeanFactoryPostProcessorTest implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        //configurableListableBeanFactory.getBeanDefinition("appcontext-service.xml");
        System.out.println("1.postProcessBeanFactory(BeanFactoryPostProcessor) 工厂后处理器, ApplicationContext容器初始化中refresh()中调用");

    }
}

InstantiationAwareBeanPostProcessor类

public class InstantiationAwareBeanPostProcessorTest implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> aClass, String s) throws BeansException {
        System.out.println("2.实例化bean之前调用,即调用bean类构造函数之前调用 " + aClass.getName());
        /*try {
            return Class.forName(""+aClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }*/ return null;//其实我不是很明白这里返回值得作用,之后可能会去深入理解

    }

    @Override
    public boolean postProcessAfterInstantiation(Object o, String s) throws BeansException {
        System.out.println("4.返回boolean,bean实例化后调用,并且返回false则不会注入属性");
        return true;
    }

    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues propertyValues, PropertyDescriptor[] propertyDescriptors, Object o, String s) throws BeansException {
        System.out.println("5.postProcessPropertyValues,在属性注入之前调用...... beanName = " + s + " 属性名集合 : " + Arrays.toString(propertyValues.getPropertyValues()));
        //System.out.println("message = " + ((HelloWorld)o).getMessage()); 这里可以看到message还是null
        return propertyValues;//这里要返回propertyValues,否则属性无法注入

    }

    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("9.postProcessBeforeInitialization(InstantiationAwareBeanPostProcessor) ");
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("13.postProcessAfterInitialization(InstantiationAwareBeanPostProcessor) ");
        return o;
    }
}

测试类

public class SpringTest {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:appcontext-*.xml");
       HelloWorld obj = (HelloWorld)context.getBean("helloWorld");
        System.out.println("14.Bean working, message = " + obj.getMessage());
        //((ClassPathXmlApplicationContext)context).refresh();
        ((ClassPathXmlApplicationContext)context).close();
    }

}

配置文件

<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
                            ">

    <context:component-scan base-package="BeanLife" />

    <bean id="helloWorld" class="BeanLife.HelloWorld" init-method="xml_init" destroy-method="xml_destroy">
        <property name="message" value="Hello World!" />
    </bean>

    <bean class="BeanLife.BeanPostProcessorTest" />
    <bean class="BeanLife.InstantiationAwareBeanPostProcessorTest" />
    <bean class="BeanLife.BeanFactoryPostProcessorTest" />
</beans>

结果代码:

八月 12, 2016 5:19:48 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@27b4fe4d: startup date [Fri Aug 12 17:19:48 CST 2016]; root of context hierarchy
八月 12, 2016 5:19:48 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [/Users/fuchaochao/joy/spring-test2/target/classes/config/spring/local/appcontext-service.xml]
1.postProcessBeanFactory(BeanFactoryPostProcessor) 工厂后处理器, ApplicationContext容器初始化中refresh()中调用
2.实例化bean之前调用,即调用bean类构造函数之前调用 com.fcc.spring.test.HelloWorld
3.HelloWorld struct.......
4.返回boolean,bean实例化后调用,并且返回false则不会注入属性
5.postProcessPropertyValues,在属性注入之前调用...... beanName = helloWorld 属性名集合 : [bean property 'message']
八月 12, 2016 5:19:48 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3ae4cdc3: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,helloWorld,com.fcc.spring.test.InitBeanPostProcessor#0,com.fcc.spring.test.InstanceBeanPostProcessor#0,com.fcc.spring.test.BeanFactoryPostProcessorTest#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
6.setBeanName(BeanNameAware) 属性注入后调用, 此时s = helloWorld
7.setBeanFactory(BeanFactory) setBeanName后调用
8.postProcessBeforeInitialization(BeanPostProcessor), bean = class com.fcc.spring.test.HelloWorld
9.postProcessBeforeInitialization(InstantiationAwareBeanPostProcessor)
10.afterPropertiesSet(InitializingBean) processBeforeInitialization之后,配置的xml_init之前调用
11.HelloWorld 初始化(init-method)
12.postProcessAfterInitialization(BeanPostProcessor), bean = class com.fcc.spring.test.HelloWorld
13.postProcessAfterInitialization(InstantiationAwareBeanPostProcessor)
14.Bean working, message = Hello World!
八月 12, 2016 5:19:48 下午 org.springframework.context.support.AbstractApplicationContext doClose
15.destroy(DisposableBean) 在processAfterInitialization之后,配置的xml_destroy之前调用
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@27b4fe4d: startup date [Fri Aug 12 17:19:48 CST 2016]; root of context hierarchy
16.HelloWorld 销毁(destroy-method)
八月 12, 2016 5:19:48 下午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3ae4cdc3: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,helloWorld,com.fcc.spring.test.InitBeanPostProcessor#0,com.fcc.spring.test.InstanceBeanPostProcessor#0,com.fcc.spring.test.BeanFactoryPostProcessorTest#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy

Process finished with exit code 0

 

Spring上下文中的Bean,如下

1.实例化: 此步骤中,bean 工厂容器从XML 配置文件中提供的bean 定义实例化bean.
2.填充属性:在此步骤中,bean 工厂容器按照XML配置文件中所指定的通过DI填充所有bean 属性。
3.设置bean 名称: 在此步骤中,在创建bean 的bean工厂中设置bean 的名称。这是通过将bean 的ID 传递给BeanNameAware 接口提供的setBeanName() 方法来完成的。
4.设置bean 工厂: 在此步骤中,为bean 提供对管理它的bean工厂的引用。这是使用BeanFactoryAware 接口的setBeanFactory() 方法来完成的。
5.预初始化: 在此步骤中,您执行在初始化bean 之前需要完成的任务。这是通过在bean类中实现BeanPostProcessor 接口并定义其postProcessBeforeInitialization 方法来完成的。
6.初始化bean: 在此步骤中,您执行某些类型的初始化任务,然后bean 才可供使用。这些任务包括打开文件、打开网络或数据库连接以及分配内存。这是通过在bean 类中实现InitiallzingBean接口并定义其afterPropertiesSet ()方法来完成的。
7.初始化后: 在此步骤中,您执行在初始化bean之后需要完成的任务。这是通过在bean 类中实现BeanPostProcessor 接口并定义其postProcessAfterInitialization() 方法来完成的。
8.bean 可供使用: 此时,bean 已准各就绪,可供应用程序使用,将留在bean工厂中,直到应用程序不再需要它。

9.销毁bean: 在此步骤中,将销毁bean。如果bean实现DisposableBean 接口,将调用destroy () 方法。然而,如果为bean声明了自定义destroy方法,将调用该方法。

 

                          

 

二 bean的作用域

<bean id="userInfo" class="cn.lovepi.UserInfo" scope="singleton"></bean>  通过scope进行配置

singleton

当定义Bean时,如果没有指定scope配置项,Bean的作用域被默认为singleton。singleton属于单例模式,在整个系统上下文环境中,仅有一个Bean实例。也就是说,在整个系统上下文环境中,你通过Spring IOC获取的都是同一个实例。

prototype作用域

当一个Bean的作用域被定义prototype时,意味着程序每次从IOC容器获取的Bean都是一个新的实例。因此,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值