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