获取Spring上下文(ApplicationContext)的三种方法

有的时候需要获取spring的上下文,通过getBean()方法获得Spring管理的Bean的对象。下面总结一下获取spring上下文的三种方式。

1 通过WebApplicationContextUtils工具类获取

ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);

其中servletContext是你需要传入的Servlet容器参数。这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。

 @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
    }

2 通过ClassPathXmlApplicationContext类获取

通过指定spring配置文件名称来获取spring上下文。

 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContex.xml");

创建一个自己的工具类(ApplicationContextHelper)实现Spring的ApplicationContextAware接口

ApplicationContextHelper实现代码如下:

@Component("applicationContextHelper")
public class ApplicationContextHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static <T> T popBean(Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    public static <T> T popBean(String name, Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(name, clazz);
    }
}

最后在springmvc配置文件中注入该bean

 <bean class="com.xxx.ApplicationContextHelper" lazy-init="false" />
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容