zoukankan      html  css  js  c++  java
  • 在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");
  • 相关阅读:
    Ubuntu
    SSH
    Markdown
    Mac OS 上的一些骚操作
    Linux Bash
    JConsole
    IDEA
    Groovy
    Github
    Git
  • 原文地址:https://www.cnblogs.com/sdjnzqr/p/4272128.html
Copyright © 2011-2022 走看看