ListenerでSpringコンテナのBeanのインスタンスを取る
1929 ワード
詳細
SSHプロジェクト開発では、Listener Listenerが使用される場合があり、Listenerでデータベースの操作を完了するなどの動作が必要な場合がありますが、その場合はSpringコンテナのBeanにListenerで使用する必要があります.Springコンテナ自体はwebです.xmlでlistener方式で起動しました.たとえばHttpSessionListenerでBeanインスタンスの注入を依存注入で完了させるには,完了できない.
1つの解決策:Spring容器の例をHttpSessionListenerでnewにより得る.次のコードがあります.
その結果、Springのコンテナを取得できますが、新しいSpringのコンテナを再生成しました.SSHプロジェクトが開始されると自動的にSpringのコンテナが1つ生成され、2つのSpringのコンテナが存在します.取るに足らない.
最良の解決策:Springが提供するWebApplicationContextUtilsによってSpringコンテナのインスタンスが得られます.コードは次のとおりです.
SSHプロジェクト開発では、Listener Listenerが使用される場合があり、Listenerでデータベースの操作を完了するなどの動作が必要な場合がありますが、その場合はSpringコンテナのBeanにListenerで使用する必要があります.Springコンテナ自体はwebです.xmlでlistener方式で起動しました.たとえばHttpSessionListenerでBeanインスタンスの注入を依存注入で完了させるには,完了できない.
1つの解決策:Spring容器の例をHttpSessionListenerでnewにより得る.次のコードがあります.
// new Spring
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
その結果、Springのコンテナを取得できますが、新しいSpringのコンテナを再生成しました.SSHプロジェクトが開始されると自動的にSpringのコンテナが1つ生成され、2つのSpringのコンテナが存在します.取るに足らない.
最良の解決策:Springが提供するWebApplicationContextUtilsによってSpringコンテナのインスタンスが得られます.コードは次のとおりです.
public class MySessionListener implements HttpSessionListener {
private Logger logger=Logger.getLogger(MySessionListener.class);
@Override
public void sessionCreated(HttpSessionEvent event) {
logger.debug(" session !!");
HttpSession session=event.getSession();
session.setAttribute(InitUtil.ISNEWSESSION, "true");
// Spring Bean 。
UsersDao userDao=(UsersDao)this.getObjectFromApplication(session.getServletContext(), "usersDaoHibernate");
System.out.println(" Dao ="+userDao);
}
/**
* WebApplicationContextUtils Spring 。 bean bean 。
* @param servletContext :ServletContext 。
* @param beanName : Spring Bean 。
* @return Bean 。
*/
private Object getObjectFromApplication(ServletContext servletContext,String beanName){
// WebApplicationContextUtils Spring 。
ApplicationContext application=WebApplicationContextUtils.getWebApplicationContext(servletContext);
// Bean 。
return application.getBean(beanName);
}
}