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

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

Spring学习五----------Bean的配置之Bean的生命周期的更多相关文章

  1. 配置Session变量的生命周期

    在Web.config文件中配置Session变量的生命周期是在<sessionState></sessionState>节中完成的,在配置Session的生命周期时,可以设置 ...

  2. 如何在web.config文件中配置Session变量的生命周期

    实例说明:在网上购物商城中,为了维护在线购物环境,一般只有注册会员才可以购买商品.实现购物功能时,先通过Session变量记录会员的登录名,然后在购买商品页面通过判断会员是否登录确定其能否购买商品. ...

  3. spring学习五:Spring Bean 定义继承

    Bean 定义继承 bean 定义可以包含很多的配置信息,包括构造函数的参数,属性值,容器的具体信息例如初始化方法,静态工厂方法名,等等. 子 bean 的定义继承父定义的配置数据.子定义可以根据需要 ...

  4. Spring学习(十九)----- Spring的五种事务配置详解

    前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较好掌握的. ...

  5. Java框架spring 学习笔记(十):bean管理(注解和配置文件混合使用)

    配置文件和注解混合使用 创建对象操作使用配置文件方式实现 注入属性的操作使用注解方式实现 编写BookDao.java和OrderDao.java文件 BookDao.java package com ...

  6. Java框架spring 学习笔记(三):Bean 的生命周期

    当一个 bean 被实例化时,它可能需要执行一些初始化使它转换成可用状态.当bean不再需要,并且从容器中移除时,需要做一些清除工作.为了定义安装和拆卸一个 bean,我们只要声明init-metho ...

  7. 【Spring学习笔记-3.1】让bean获取spring容器上下文(applicationContext.xml)

    *.hl_mark_KMSmartTagPinkImg{background-color:#ffaaff;}*.hl_mark_KMSmartTagBlueImg{background-color:# ...

  8. Spring Boot实践——用外部配置填充Bean属性的几种方法

    引用:https://blog.csdn.net/qq_17586821/article/details/79802320 spring boot允许我们把配置信息外部化.由此,我们就可以在不同的环境 ...

  9. spring源码学习五 - xml格式配置,如何解析

    spring在注入bean的时候,可以通过bean.xml来配置,在xml文件中配置bean的属性,然后spring在refresh的时候,会去解析xml配置文件,这篇笔记,主要来记录.xml配置文件 ...

随机推荐

  1. docke存储

    1.Docker提供三种不同的方式将数据从宿主机挂载到容器中:volumes,bind mounts和tmpfs.volumes:Docker管理宿主机文件系统的一部分(/var/lib/docker ...

  2. 【04】Vue 之 事件处理

    4.1. 监听事件的Vue处理 Vue提供了协助我们为标签绑定时间的方法,当然我们可以直接用dom原生的方式去绑定事件.Vue提供的指令进行绑定也是非常方便,而且能让ViewModel更简洁,逻辑更彻 ...

  3. DOS的一些常用命令

    原文发布时间为:2011-02-12 -- 来源于本人的百度文章 [由搬家工具导入] DOS远程桌面连接命令 mstsc /v: 192.168.1.250 /console cmd        运 ...

  4. [LeetCode] Search Insert Position 二分搜索

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  5. AC日记——[Sdoi2010]星际竞速 bzoj 1927

    1927 思路: 连边,拆点: 每个点拆成i,i+n,都向t连边: i到t表示高速模式,i+n到t表示跳跃模式: 然后读入路径,如果u>v,则交换u,v: u向v+n连边: spfa跑最小费用: ...

  6. Bootstrap多层模态框modal嵌套问题

    一.问题 在项目里忽然新加了一个需求,在原本弹出的模态框里,点击模态框里面的按钮再弹出一个模态框,出来另个模态框来展示详细信息.此时就存在两个模态框在这个需求没加之前有一个弹出的模态框也是需要继续点击 ...

  7. EOJ Monthly 2018.7

    准备继续大学acm啦 又要开始愉快的码码码啦 第一次在华东师大OJ上面做题 看来EOJ上的积分体质是假的,我怎么一把上红??? A.数三角形 神tm的防AK题放在A,出题人很不友好啊... 先写了个暴 ...

  8. Graphs (Cakewalk) 1 B - medium

    Discription Bear Limak examines a social network. Its main functionality is that two members can bec ...

  9. SQL SERVER 技术博客 外文

    https://www.sqlskills.com/blogs/paul/capturing-io-latencies-period-time/ http://www.sqlskills.com/bl ...

  10. pt-online-schema-change原理解析(转)

    pt-online-schema-change原理解析 博客相关需要阅读 - zengkefu - 博客园 .pt-online-schema-change工具的使用限制: ).如果修改表有外键,除非 ...