前两天再写监听器的时候,发现了一个异常javax.naming.NamingException: Cannot create resource instance,出现这个异常是由于,你所用的对象是经过注解方式注入进来的,可是此时,你的spring容器尚未启动完成,因此才会报错,解决方法是,先定义你注入的内容(记住不要加@resource),好比:java
private ChatService chatService;
而后再用WebApplicationContextUtils来实例化你的属性就能够了web
public void contextInitialized(ServletContextEvent arg0) { chatService=WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()) .getBean(ChatService.class); }
还有一点要记住的,在web.xml文件中添加你的监听器的时候,记得要放在spring
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
spring监听器以后,不然会报错code