在web.xml中配置了MyListener,MyListener中有个myService,有个setMyService方法,在xml文件中配置了
<bean id="myListener" class="com.MyListener" scope="prototype">
<property name="myService" ref="myService"/>
</bean>
但是MyListener中的那个myService一直都是null,我该怎么注入?

解决方案 »

  1.   


    参考:http://topic.csdn.net/u/20090608/17/669e10c2-30c7-47e9-baed-2bf3dfc8cb26.html
      

  2.   


    ServletContext sc = request.getSession(true).getServletContext();
    ApplicationContext beans = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    MyService service = (MyService) beans.getBean("myService");
    以上代码就可以啦。 你在监听器里可以用service了。 可能不满足你的要求,这毕竟不是注入。我不知道是否可以注入,我一般都是这么干的。
      

  3.   


    你的做法跟2楼的做法差不多,拿到那个service了。问个问题,一般项目中自己写的Listener会很多吗?
      

  4.   

    那你的myService已经配置了吗?一般注入的都是普通的bean啊,如果是Listener就不一定对了。因为Listener在容器启动时会初始化,而容器启动时也会读取applicationcontext.xml进行bean的装配。
      

  5.   

    你这个是Spring吧,Spring的配置内容要放在Spring的配置文件里,如app-servlet.xml里,不是放在web.xml中
      

  6.   


    是Listener 已经用getBean方法拿到了service
      

  7.   

    嗯。 我也不知道Linstener能不能放到Ioc容器里面去。 如果能放进去的话还是可以注入的。