Java普通類中獲取Spring管理的實例 幾種簡單方式


第一種方式依賴於ServletContext,所以要先獲取Request

在web.xml中配置springRequest監聽器

<listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
</listener>

定義個靜態方法調用工具類方便調用

public static Object getBean(String name) {
        ServletContext servletContext = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        return ac.getBean(name);
    }

第二種方法不依賴於servlet,不需要注入的方式 注意一點,在服務器啟動時,Spring容器初始化時,不能通過以下方法獲取Spring 容器

public static Object getBean2(String name) {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        return wac.getBean(name);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM