目录结构
代码
package dao;
public interface BookDao {
public void save();
}
在BookDaoimpl中添加init()和destroy()
package dao.impl;
import dao.BookDao;
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
//表示bean初始化对应的操作
public void init(){
System.out.println("book dao init...");
}
//表示bean销毁前对应的操作
public void destory(){
System.out.println("book dao destory...");
}
}
package service;
public interface BookService {
public void save();
}
BookServiceImpl重写InitializingBean,DisposableBean的方式来实现init() 和destroy()
package service.impl;
import dao.BookDao;
import service.BookService;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
System.out.println("set .....");
this.bookDao = bookDao;
}
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
public void destroy() throws Exception {
System.out.println("service destroy");
}
public void afterPropertiesSet() throws Exception {
System.out.println("service init");
}
}
在bookDaoImpl 中要指明init 和destroy方法,而在实现了接口的bookService中则不用指明
<?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="bookDao" class="dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"/>
<bean id="bookService" class="service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"></property>
</bean>
</beans>
ctx的类型不是ApplicationContext,而是ClassPathXmlApplicationContext
import dao.BookDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppForLifeCycle {
public static void main( String[] args ) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
//注册关闭钩子函数,在虚拟机退出之前回调此函数,关闭容器
ctx.registerShutdownHook();
//关闭容器
// ctx.close();
}
}
运行结果:
bean的生命周期
初始化容器
1. 创建对象(内存分配)
2.执行构造方法
3.执行属性注入方法(set 操作)
使用bean
1.执行业务操作
销毁容器
1.执行bean的销毁方法
容器关闭方式 (容器关闭前触发bean的销毁)
ctx.close()
ctx.registrerShutHook()