在listener或者工具中使用spring容器中的bean实例

在项目中经常遇见需要在Listener中或者工具中使用Spring容器中的bean实例,由于bean不能在stataic的类中使用。

介绍一种方式:

public class SpringTool {
    
    public static Object getObjectFromApplication(HttpSession session,String beanName){  
        ServletContext servletContext= session.getServletContext();
        //通过WebApplicationContextUtils 得到Spring容器的实例。  
        WebApplicationContext application=WebApplicationContextUtils.getWebApplicationContext(servletContext);   
        //返回Bean的实例。  
        return application.getBean(beanName);  
    } 
}

 

使用举例:

LoginService loginService=(LoginService) SpringTool.getObjectFromApplication(session, "loginService");
posted @ 2015-02-04 13:26  正正杂说  阅读(216)  评论(0编辑  收藏  举报