1、加载bean时,可以设置一个类初始化的方法和销毁bean时的方法。
<bean class="cn.com.dao.impl.UserDaoMySqlImpl" init-method="init" destroy-method="destroy"/>
2、使用spring的注解
@PostConstruct
public void init(){
System.out.println("userService init");
o.getUser();
}
@PreDestroy
public void destroy(){
System.out.println("userService destroy");
}
3、web.xml中配置
<listener>
<listener-class>com.epoch.customizeproject.scnt.servlet.SynUserServlet</listener-class>
</listener>
然后:实现接口 ServletContextListener重写contextInitialized方法
public void contextInitialized(ServletContextEvent event) {
WebApplicationContext applicationContext=WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
UserService userService = (UserService)applicationContext.getBean(UserService.class);
//这样就可以获取bean了
}

本文介绍了如何在Spring框架中管理Bean的生命周期,包括初始化和销毁阶段。通过XML配置文件定义init-method和destroy-method属性来指定相应的回调方法,并展示了使用@PostConstruct和@PreDestroy注解进行相同操作的方式。此外,还提供了在web.xml中配置监听器来获取ApplicationContext并使用Bean的示例。
703

被折叠的 条评论
为什么被折叠?



