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);
    }
posted @ 2020-07-20 17:24  MelodyJerry  阅读(754)  评论(0)    收藏  举报
没有伞的孩子必须努力奔跑!|
载入天数...载入时分秒...
(っ•̀ω•́)っ✎⁾⁾ 开心每一天