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();
}
测试结果: