• spring项目中 通过自定义applicationContext工具类获取到applicationContext上下文对象


    spring项目在服务器启动的时候 spring容器中就已经被创建好了各种对象,在我们需要使用的时候可以进行调用.

    工具类代码如下

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    
    @Component("applicationContextHelper")
    public class ApplicationContextHelper implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext;
    
        // spring容器中配置bean之后,会在项目启动的时候给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);
        }
    }

    接着就是在spring配置文件中配置该bean , 并关掉懒加载,让项目初始化的时候就给applicationContext对象赋上值

    测试:

     

    我们可以通过工具类直接拿到spring容器中的对象,这是因为在初始化项目的时候我们给工具类中的spring上下文属性applicationContext赋上了值。

     

  • 相关阅读:
    ZJOI2017
    李超线段树
    单调性优化dp
    ZJOI2018 树
    【ZJOI2017】汉诺塔
    暂存
    聚类的方法(层次聚类,K-means聚类)
    哈希表(散列表)
    多路查找树B树
    二叉排序树
  • 原文地址:https://www.cnblogs.com/devise/p/9974658.html
Copyright © 2020-2023  润新知