spring6:bean的生命始末方法

49 篇文章 0 订阅

 

package com.atChina2.service;

public class SomeServiceImpl implements SomeService {

	public SomeServiceImpl(){
		System.out.println("SomeServiceImpl...无参构造函数..");
	}
	
	@Override
	public void doSome() {
		System.out.println("doSome业务方法...");
	}
	
	// 定义bean的生命始末方法,自定义方法参与到spring创建和销毁对象的过程中。
	// 初始化方法
	public void startUp(){
		System.out.println("bean的初始化方法,可以完成构造方法的功能,给属性赋值,初始化其他对象");
	}
	
	// bean销毁之前执行的方法
	public void endDown(){
		System.out.println("bean对象销毁之前执行的方法,清楚对象,释放内存");
	}
}

 

 配置bean的init-method,destroy-method属性

<?xml version="1.0" encoding="UTF-8"?>
<!-- 引用Spring的多个Schema空间的格式定义文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd ">

	<!-- 定义bean的生命始末方法,自定义方法参与到spring创建和销毁对象的过程中。
	      1>. 在java类中定义方法,方法的原形: public void 方法名(无参数){...} 
	      2>. 在定义bean的时候,告诉spring两个方法的存在
	      <bean id="xx" class="yy" 
	         init-method="" destroy-method="" />
	      -->
	<bean id="someService" class="com.atChina2.service.SomeServiceImpl" init-method="startUp" destroy-method="endDown" scope="singleton"/>

</beans>

测试方法:

// 获取容器中对象信息
		@Test
		public void test3(){
			String configLocation = "applicationContext.xml"; // 类路径的根目录
			// 会创建对象
			ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);
			
			com.atChina2.service.SomeService ss = (com.atChina2.service.SomeService)ctx.getBean("someService");
			ss.doSome();
			
			/*
			 * 销毁方法的执行
			 * 1. 关闭容器,关闭容器时会通知容器中的单例对象,调用对象自己的销毁方法
			 * 2. 对象必须是单例的
			 * */
			((ClassPathXmlApplicationContext)ctx).close();
		}

测试结果: 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值