zoukankan      html  css  js  c++  java
  • 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赋上了值。

     

  • 相关阅读:
    50.2 Django 连接MySQL,django orm 数据库(models)操作
    50.1 Django 静态资源配置 static && form表单和 request对象
    JS备忘
    Python 单元测试 生产HTML测试报告
    python 单元测试 执行测试
    pycharm 安装插件
    Python 单元测试 实战演练
    Python 单元测试
    Pycharm 使用备忘
    Python 异常
  • 原文地址:https://www.cnblogs.com/devise/p/9974658.html
Copyright © 2011-2022 走看看