【问题标题】:call a service layer function in Listener class on Session destroyed in Spring在 Spring 中销毁的 Session 上调用 Listener 类中的服务层函数
【发布时间】:2012-12-12 09:10:30
【问题描述】:

我在 web.xml 中配置了一个监听器

<listener>
      <listener-class>com.Mylistener</listener-class>
</listener>

MyListener.java

有以下代码

 public class MyListener extends HttpSessionEventPublisher{

           myServiceInterface myService;

           @Override
           public void sessionCreated(HttpSessionEvent event) {     
              super.sessionCreated(event);
           }

           @Override
           public void sessionDestroyed(HttpSessionEvent event) {
             //Call a method from service layer which is communicating with DAO layer and then database.
    super.sessionDestroyed(event);
           }

    }

该服务已经有自己的映射并且工作正常。

什么其他映射,我需要在 Mylistener 中调用服务层,上面的代码根本不起作用

【问题讨论】:

  • 你有什么错误吗?
  • 是的,如果我直接使用它,那么它会在调用 DAO 层时抛出 NULLPOINTER 异常,因为我们没有在任何地方实例化 DAO 对象。一般我们在 XML 文件中做

标签: java spring model-view-controller session listener


【解决方案1】:
public class MyListener extends HttpSessionEventPublisher {
    @Override
    public void sessionDestroyed(final HttpSessionEvent event) {
        final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(event.getSession().getServletContext());
        final MyServiceInterface service = ctx.getBean(MyServiceInterface.class);
        // use service
        super.sessionDestroyed(event);
    }
}    

应该可以工作(未经测试)。

【讨论】:

  • final ApplicationContext ctx = this.getContext(event.getSession().getServletContext());此行抛出编译错误“HttpSessionEventPublisher 类型的方法 getContext(ServletContext) 不可见”。
  • 对,包保护,抱歉;你可以在你的子类中做同样的事情(我的意思是复制方法体)。我更新了我的答案。
  • 非常感谢您帮助我..:)
猜你喜欢
  • 2017-02-23
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多