監聽器javax.naming.NamingException

前兩天再寫監聽器的時候,發現了一個異常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

相關文章
相關標籤/搜索