zoukankan      html  css  js  c++  java
  • 怎么随时获取Spring的上下文ApplicaitonContext,和Spring管理的Bean

    BeanFactory接口

    Interface BeanFactory

    getBean

    <T> T getBean(String name,
                  Class<T> requiredType)
              throws BeansException
    上面
    是Apring的bean工厂的接口(顾名思议 拿到Spring的Bean) 下面看它的一个实现类

    ClassPathXmlApplicationContext(BeanFactory接口的一个实现类)

    public ClassPathXmlApplicationContext(String configLocation)
                                   throws BeansException
    Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML file and automatically refreshing the context.
    构造方法的参数 是Spring Bean配置的xml路径(src下面的路径)
    然后 我们就可以通过new 一个ClassPathXmlApplicationContext 然后调用BeanFactory的getBean()方法获取Spring管理的Bean了 

    上面只是通过API说了Spring获取Bean的原理,然而工作中:

    在平时代码中 我们都是通过 @Autowired 来引入一个对象。也就是Spring的依赖注入。

    不过使用依赖注入需要满足两个条件,注入类 和被注入类 都需要交给Spring去管理,也就是需要在Spring中配置Bean

    但是开发中,有些工具类(或者实体类)是不需要在Spring中配置的,如果工具类里面 想引用Spring配置的Bean 应该怎么办

    解决办法

    自己用的时候主动去new。 不可取 自己new的类 没有交给Spring去管理,如果类中 用到了Spring的一些注解功能 完全失效  

    也不可能像上面API中 去通过XML拿(IO操作很费时间)

    工作中使用ApplicationContextAware接口

    先通过setApplicationContext获取Spring的上下文

    在通过applicationContext去获取Spring管理的Bean

    写一个SpringContextUtils专门去获取Spring管理的Bean。也就是说 被注入对象 可以不交给Spring管理,就可以获取Spring管理的Bean

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    public class SpringContextUtils implements ApplicationContextAware { 
    
        private static ApplicationContext applicationContext;
        /**
         * 如果实现了ApplicationContextAware接口,在Bean的实例化时会自动调用setApplicationContext()方法
         */
        @Override
        public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
            SpringContextUtils.applicationContext = applicationContext;
        }
        
        public static <T> T getBean(Class<T> clazz) {
            return applicationContext.getBean(clazz);
        }
    
    
    }

    注意点

     SpringContextUtils必须在Spring中配置bean(也就是SpringContextUtils必须交给Spring管理) 不然 在Bean的实例化时不会自动调用setApplicationContext()方法

     SpringContextUtils中的ApplicationContext需要是static的

    这样 我们就可在任何代码任何地方任何时候中取出ApplicaitonContext. 从而获取Spring管理的Bean

  • 相关阅读:
    echarts设置y轴线的样式
    echarts基础配置信息?
    提高网站用户体验使网站更好发展的五大要点
    没有或很少有出站链接的网站存在致命的缺陷
    网络推广之百度知道推广技巧
    如何让百度3分钟内收录你的文章
    CSS强制换行
    如何提高网站在搜索引擎中的权重
    js闭包深入详解
    深入浅出之正则表达式
  • 原文地址:https://www.cnblogs.com/ssskkk/p/9178338.html
Copyright © 2011-2022 走看看