• Spring学习五----------Bean的配置之Bean的生命周期


    © 版权声明:本文为博主原创文章,转载请注明出处

    Bean的生命周期

    1.定义

    2.初始化

    3.使用

    4.销毁

    初始化和销毁的三种方式

    1.实现org.springframework.beans.factory.InitializingBean和org.springframework.beans.factory.DisposableBean接口

    2.配置init-method和destroy-method

    3.配置全局默认初始化和销毁方法default-init-method和default-destroy-method

    实例

    1.项目结构

    2.pom.xml

    <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>org.spring</groupId>
    	<artifactId>Spring</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>Spring</name>
    	<url>http://maven.apache.org</url>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<spring.version>4.3.7.RELEASE</spring.version>
    	</properties>
    
    	<dependencies>
    		<!-- junit依赖 -->
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>4.12</version>
    			<scope>test</scope>
    		</dependency>
    		<!-- spring依赖 -->
    		<dependency>
    		    <groupId>org.springframework</groupId>
    		    <artifactId>spring-core</artifactId>
    		    <version>${spring.version}</version>
    		</dependency>
    		<dependency>
    		    <groupId>org.springframework</groupId>
    		    <artifactId>spring-beans</artifactId>
    		    <version>${spring.version}</version>
    		</dependency>
    		<dependency>
    		    <groupId>org.springframework</groupId>
    		    <artifactId>spring-context</artifactId>
    		    <version>${spring.version}</version>
    		</dependency>
    		<dependency>
    		    <groupId>org.springframework</groupId>
    		    <artifactId>spring-web</artifactId>
    		    <version>${spring.version}</version>
    		</dependency>
    		<dependency>
    		    <groupId>org.springframework</groupId>
    		    <artifactId>spring-webmvc</artifactId>
    		    <version>${spring.version}</version>
    		</dependency>
    		
    	</dependencies>
    </project>
    

    3.spring-beanlifecycle.xml(三选一)

      3.1 实现org.springframework.beans.factory.InitializingBean和org.springframework.beans.factory.DisposableBean接口

    <?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 id="beanLifeCycle" class="org.spring.bean.BeanLifeCycle"/>        
            
    </beans>
    

      3.2 配置init-method和destroy-method

    <?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 id="beanLifeCycle" class="org.spring.bean.BeanLifeCycle"
    		init-method="start" destroy-method="stop"/>        
            
    </beans>
    

      3.3 配置全局默认初始化和销毁方法default-init-method和default-destroy-method

    <?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"
            default-init-method="defaultInit" default-destroy-method="defaultDestroy">
            
    	<bean id="beanLifeCycle" class="org.spring.bean.BeanLifeCycle"/>        
            
    </beans>

    4.BeanLifeCycle.java(三选一)

      4.1 实现org.springframework.beans.factory.InitializingBean和org.springframework.beans.factory.DisposableBean接口

    package org.spring.bean;
    
    import org.springframework.beans.factory.DisposableBean;
    import org.springframework.beans.factory.InitializingBean;
    
    public class BeanLifeCycle implements InitializingBean, DisposableBean {
    
    	/**
    	 * 初始化
    	 */
    	public void afterPropertiesSet() throws Exception {
    		
    		System.out.println("Bean Init.");
    		
    	}
    
    	/**
    	 * 销毁
    	 */
    	public void destroy() throws Exception {
    		
    		System.out.println("Bean Destroy.");
    		
    	}
    
    }
    

      4.2 配置init-method和destroy-method

    package org.spring.bean;
    
    public class BeanLifeCycle {
    
    	/**
    	 * 初始化
    	 */
    	public void start() throws Exception {
    		
    		System.out.println("Bean Start.");
    		
    	}
    
    	/**
    	 * 销毁
    	 */
    	public void stop() throws Exception {
    		
    		System.out.println("Bean Stop.");
    		
    	}
    
    }
    

      4.3 配置全局默认初始化和销毁方法default-init-method和default-destroy-method

    package org.spring.bean;
    
    public class BeanLifeCycle {
    
    	/**
    	 * 初始化
    	 */
    	public void defaultInit() throws Exception {
    		
    		System.out.println("Bean DefaultInit.");
    		
    	}
    
    	/**
    	 * 销毁
    	 */
    	public void defaultDestroy() throws Exception {
    		
    		System.out.println("Bean DefaultDestroy.");
    		
    	}
    
    }
    

    5.UnitTestBase

    package org.spring.ioc.test;
    
    import org.junit.After;
    import org.junit.Before;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.util.StringUtils;
    
    /**
     * 单元测试初始化类
     *
     */
    public class UnitTestBase {
    	
    	private ClassPathXmlApplicationContext context;
    	private String springXmlPath;
    	
    	/**
    	 * 无参构造器
    	 */
    	public UnitTestBase() {
    		
    	}
    
    	/**
    	 * 含参构造器
    	 * 
    	 * @param springXmlPath
    	 * 						spring配置文件路径
    	 */
    	public UnitTestBase(String springXmlPath) {
    		
    		this.springXmlPath = springXmlPath;
    		
    	}
    	
    	/**
    	 * 初始化spring配置文件
    	 */
    	@Before//在@Test注解的方法执行前执行
    	public void before() {
    		
    		if(StringUtils.isEmpty(springXmlPath)) {//默认spring配置文件路径
    			springXmlPath = "classpath*:spring-*.xml";
    		}
    		//加载配置文件,一个context表示一个容器
    		context = new ClassPathXmlApplicationContext(springXmlPath.split("[,\s]+"));
    		//启动组件
    		context.start();
    		
    	}
    	
    	/**
    	 * 销毁spring组件
    	 */
    	@After//在@Test注解的方法执行后执行
    	public void after() {
    		
    		context.destroy();//销毁组件
    		
    	}
    	
    	/**
    	 * 获取spring中定义的bean实例
    	 * 
    	 * @param beanId
    	 * 					
    	 * @return
    	 */
    	@SuppressWarnings("unchecked")
    	protected <T extends Object> T getBean(String beanId) {
    		
    		return (T) context.getBean(beanId);
    		
    	}
    	
    	/**
    	 * 获取spring中定义的bean实例
    	 * 
    	 * @param clazz
    	 * 				
    	 * @return
    	 */
    	protected <T extends Object> T getBean(Class<T> clazz) {
    		
    		return (T) context.getBean(clazz);
    		
    	}
    
    }
    

    6.TestBeanLifeCycle

    package org.spring.ioc.test;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.junit.runners.BlockJUnit4ClassRunner;
    import org.spring.bean.BeanLifeCycle;
    
    @RunWith(BlockJUnit4ClassRunner.class)//指定JUnit默认执行类
    public class TestBeanLifeCycle extends UnitTestBase {
    	
    	public TestBeanLifeCycle() {//通过构造方法传入spring配置文件路径
    		
    		super("classpath*:spring-beanlifecycle.xml");
    		
    	}
    	
    	@Test
    	public void testScope() {
    		
    		BeanLifeCycle bean = super.getBean("beanLifeCycle");
    		
    	}
    	
    }
    

    7.效果预览

      7.1 实现org.springframework.beans.factory.InitializingBean和org.springframework.beans.factory.DisposableBean接口

      7.2 配置init-method和destroy-method

      7.3 配置全局默认初始化和销毁方法default-init-method和default-destroy-method

      7.4 三种方式一起执行

    8.总结

      1)实现接口方式的初始化和销毁 先于 配置init-method和destroy-method

      2)当 实现接口方式的初始化和销毁或配置init-method和destroy-method 时,配置全局默认初始化和销毁方法default-init-method和default-destroy-method不生效

    参考:http://www.imooc.com/video/3751

  • 相关阅读:
    Windows 无法启动xx服务 错误1053:服务没有及时响应启动或控制请求
    Nginx之解压编译安装-yellowcong
    SqlServer中的数据类型UniqueIdentifier
    Android利用Volley异步载入数据完整具体演示样例(二)
    蓝桥杯——历年真题之带分数
    联想教育应用使用说明(7.6版本号)——第4章 网络控制工具的使用
    oracle入门学习笔记
    Asp.Net实现JS前台带箭头的流程图方法总结!(个人笔记,信息不全)
    到底什么是RPC?
    Codeforces Round #336 (Div. 2) 608C Chain Reaction(dp)
  • 原文地址:https://www.cnblogs.com/jinjiyese153/p/6694761.html
Copyright © 2020-2023  润新知