BookDaoImpl
在方法上加上初始化和销毁前执行注解来控制生命周期
- <font style="color:red"> 注意:</font > 在单例模式下执行
@SuppressWarnings("all") | |
@Repository | |
@Scope("singleton") | |
public class BookDaoImpl implements BookDao { | |
public void save(){ | |
System.out.println("BookDaoImpl save rning..."); | |
} | |
@PostConstruct | |
public void init(){ | |
System.out.println("bookdaoimpl init rning..."); | |
} | |
@PreDestroy | |
public void destroy(){ | |
System.out.println("bookdaoimpl destroy rning..."); | |
} | |
} |
测试代码
public void test(){ | |
ApplicationContext c = new AnnotationConfigApplicationContext(SpringConfig.class); | |
BookDao dao = c.getBean(BookDao.class); | |
System.out.println(dao); | |
BookDao dao1 = c.getBean(BookDao.class); | |
System.out.println(dao1); | |
dao.save(); | |
} |
Run Result
设置关闭钩子:registerShutdownHook
测试代码
public void test(){ | |
// ApplicationContext 中不具有 registerShutdownHook 关闭钩子的方法 | |
AnnotationConfigApplicationContext c = new AnnotationConfigApplicationContext(SpringConfig.class); | |
// 设置关闭钩子 | |
c.registerShutdownHook(); | |
BookDao dao = c.getBean(BookDao.class); | |
System.out.println(dao); | |
BookDao dao1 = c.getBean(BookDao.class); | |
System.out.println(dao1); | |
dao.save(); | |
} |
Run Result