<span>Java普通类中获取Spring管理的实例 几种简单方式</span>

第一种方式依赖于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);
    }
全部评论

相关推荐

不愿透露姓名的神秘牛友
2025-11-27 14:30
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务