Spring点滴四:Spring Bean生命周期

Posted 阿四

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring点滴四:Spring Bean生命周期相关的知识,希望对你有一定的参考价值。

Spring Bean 生命周期示意图:

   了解Spring的生命周期非常重要,我们可以利用Spring机制来定制Bean的实例化过程。

---------------------------------------------------------------------------------------------------------------------------------------------------

spring-service.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
     <!-- 定义一个bean -->
     <bean id="narCodeService" class="com.test.service.impl.NarCodeServiceImpl">
     </bean>
   
    <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
 
    <bean id="beanLifecycle" class="com.test.spring.BeanLifecycle" init-method="init" destroy-method="close">
        <property name="name" value="张三"></property>
        <property name="sex" value="男"></property>
    </bean>
    
    <bean id="postProcessor" class="com.test.spring.PostProcessor"/> </beans>

Service Class:

package com.test.spring;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
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.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;

import com.sun.org.apache.xml.internal.security.Init;

/**
 * 测试Spring Bean的生命周期
 * @author zss
 *
 */
public class BeanLifecycle implements InitializingBean,DisposableBean
,BeanFactoryAware,BeanNameAware,ApplicationContextAware{
    private String name;
    private String sex;
    
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("》》》调用BeanLifecycle对象"+this.getName()+"属性set方法,设值为:"+name);
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        System.out.println("》》》调用BeanLifecycle对象"+this.getSex()+"属性set方法,设值为:"+sex);
        this.sex = sex;
    }
    /**
     * 依次开始调用初始化回调方法
     */
    @PostConstruct
    public void initPostConstruct(){
        System.out.println("》》》注解初始化方法被调用");
    }
    
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("》》》BeanLifecycle调用了InitailizingBean的afterPorpertiesSet方法了.....");
    }
    
    public void init (){
        System.out.println("》》》init方法被调用");
    }

    /**
     * 依次开始调用销毁回调方法
     */
    
    @PreDestroy
    public void preDestroy(){
        System.out.println("》》》注解销毁方法被调用");
    }
    
    @Override
    public void destroy() throws Exception {
        System.out.println("》》》BeanLifecycle从Spring IoC容器中移除了.......");
    }
    public void  close() {
        System.out.println("》》》close方法被调用");
    }

    @Override
    public void setApplicationContext(ApplicationContext paramApplicationContext)
            throws BeansException {
        System.out.print("》》》调用ApplicationContextAware接口setApplicationContext方法:");
        System.out.println(paramApplicationContext);    
        
    }

//    @Override
//    public void setResourceLoader(ResourceLoader paramResourceLoader) {
//        System.out.print("》》》调用ResourceLoaderAware接口setResourceLoader方法:");
//        System.out.println(paramResourceLoader);        
//    }

//    @Override
//    public void setImportMetadata(AnnotationMetadata paramAnnotationMetadata) {
//        System.out.println(333333);        
//    }

//    @Override
//    public void setEnvironment(Environment paramEnvironment) {
//        System.out.print("》》》调用EnvironmentAware接口setEnvironment方法:");
//        System.out.println(paramEnvironment);        
//    }

    @Override
    public void setBeanName(String paramString) {
        System.out.println("》》》调用BeanNameAware接口setBenaName方法: "+paramString);
        
    }

    @Override
    public void setBeanFactory(BeanFactory paramBeanFactory)
            throws BeansException {
        
        System.out.print("》》》调用BeanFactoryAware接口setBeanFactory方法:");
        System.out.println(paramBeanFactory);
        
    }

//    @Override
//    public void setBeanClassLoader(ClassLoader paramClassLoader) {
//        System.out.print("》》》调用BeanClassLoaderAware接口setBeanClassLoader方法:");
//        System.out.println(paramClassLoader);        
//    }

//    @Override
//    public void setApplicationEventPublisher(
//            ApplicationEventPublisher paramApplicationEventPublisher) {
//        System.out.print("》》》调用ApplicationEventPublisherAware接口setApplicationEventPublisher方法:");
//        System.out.println(paramApplicationEventPublisher);    
//    }

    @Override
    public String toString() {
        return "BeanLifecycle [name=" + name + ", sex=" + sex + "]";
    }

    
}

 

Test:

package com.test.spring;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class T {
    ClassPathXmlApplicationContext applicationcontext=null;
    @Before
    public void before() {
        System.out.println("》》》Spring ApplicationContext容器开始初始化了......");
        applicationcontext= new ClassPathXmlApplicationContext(new String[]{"test1-service.xml"});
        System.out.println("》》》Spring ApplicationContext容器初始化完毕了......");
    }
    @Test
    public void  test() {
        BeanLifecycle beanLifecycle =applicationcontext.getBean("beanLifecycle",BeanLifecycle.class);
        //applicationcontext.close();
        applicationcontext.registerShutdownHook();   
    }
}

测试结果:

》》》Spring ApplicationContext容器开始初始化了......
2017-03-19 00:08:01  INFO:ClassPathXmlApplicationContext-Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6c7e6b26: startup date [Sun Mar 19 00:08:01 CST 2017]; root of context hierarchy
2017-03-19 00:08:01  INFO:XmlBeanDefinitionReader-Loading XML bean definitions from class path resource [test1-service.xml]
》》》调用BeanLifecycle对象null属性set方法,设值为:张三
》》》调用BeanLifecycle对象null属性set方法,设值为:男
》》》调用BeanNameAware接口setBenaName方法: beanLifecycle
》》》调用BeanFactoryAware接口setBeanFactory方法:org.springframework.beans.factory.support.DefaultListableBeanFactory@75a6bd5: defining beans [narCodeService,org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#0,beanLifecycle,postProcessor]; root of factory hierarchy
》》》调用ApplicationContextAware接口setApplicationContext方法:org.springframework.context.support.ClassPathXmlApplicationContext@6c7e6b26: startup date [Sun Mar 19 00:08:01 CST 2017]; root of context hierarchy
后置处理器处理bean=【beanLifecycle】开始
》》》注解初始化方法被调用
BeanLifecycle [name=张三, sex=男]
》》》BeanLifecycle调用了InitailizingBean的afterPorpertiesSet方法了.....
BeanLifecycle [name=张三, sex=男]
》》》init方法被调用
后置处理器处理bean=【beanLifecycle】完毕!
》》》Spring ApplicationContext容器初始化完毕了......
2017-03-19 00:08:03  INFO:ClassPathXmlApplicationContext-Closing org.springframework.context.support.ClassPathXmlApplicationContext@6c7e6b26: startup date [Sun Mar 19 00:08:01 CST 2017]; root of context hierarchy
》》》注解销毁方法被调用
》》》BeanLifecycle从Spring IoC容器中移除了.......
》》》close方法被调用

 

关于Spring BeanPostProcessor(后置处理器)讲解请查看:http://www.cnblogs.com/sishang/p/6576665.html

以上是关于Spring点滴四:Spring Bean生命周期的主要内容,如果未能解决你的问题,请参考以下文章

Bean的生命周期

Spring基础:Bean的生命周期

Spring的Bean初始化过程和生命周期

Spring Bean的生命周期

Spring Bean的生命周期

Java面试小短文Spring Bean生命周期的执行流程