美文网首页
获取Spring上下文(ApplicationContext)的

获取Spring上下文(ApplicationContext)的

作者: embers1996 | 来源:发表于2018-09-17 16:50 被阅读0次

    有的时候需要获取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" />
    

    相关文章

      网友评论

          本文标题:获取Spring上下文(ApplicationContext)的

          本文链接:https://www.haomeiwen.com/subject/fccrnftx.html