Spring初始化bean或销毁bean时,有时需要作一些处理工作,因此spring可以在创建和拆卸bean的时候调用bean的两个生命周期方法
具体是通过编辑Spring的配置文件来实现,加入2个属性
- init-method :当bean被载入到容器的时候调用init-method属性指定的方法
- destroy-method: 当bean从容器中删除的时候调用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">
<!-- 添加具体的类,id相当于key,可随意起名,class必须是完整类路径名 -->
<bean id="userService" class="blog.csdn.net.mchenys.service.impl.UserServiceImpl"
init-method="onCreate" destroy-method="onDestory"></bean>
</beans>
接着在UserServiceImpl类中添加对应的2个方法
package blog.csdn.net.mchenys.service.impl;
import blog.csdn.net.mchenys.service.UserService;
public class UserServiceImpl implements UserService{
//初始化方法
public void onCreate() {
System.out.println("UserServiceImpl 初始化");
}
//销毁方法
public void onDestory() {
System.out.println("UserServiceImpl 销毁");
}
@Override
public void sayHello() {
System.out.println("hello spring");
}
}
测试方法
@Test
public void test2() {
// 创建Spring的工厂类:
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
// 通过工厂解析XML获取Bean的实例.
UserService userService = (UserService) applicationContext.getBean("userService");
userService.sayHello();
//关闭工厂,仅测试使用,关闭后,工厂中的所有bean都会被释放
applicationContext.close();
}
执行后,控制台会看到下面的log
ok,这样就配置完成了.