在静态方法中使用Spring上下文

使用场景

  • 在某些工具类中需要使用Spring的ApplicationContext来获取相关的Bean来实现
  • 静态方法需要使用静态成员变量,而如果是静态的ApplicationContext没法通过@Autowired等注解注入进来

通过ApplicationContextAware获取ApplicationContext

ApplicationContextAwareSpring中提供的接口,实现该接口的类Spring将会把ApplicationContext通过setApplicationContext方法注入该类。

@Component
public class CxtDemo implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

在静态方法中使用

通过上述方法我们已经拿到ApplicationContext,这样的话我们我们只需把类成员声明为static就可以

@Component
public class CxtDemo implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    
    //静态方法
    public static Object doSomethings(){
        // you can use applicationContext here  
        ...
    } 

    // 提供获取方法
    public static ApplicationContext applicationContext(){
       return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,247评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,222评论 6 342
  • 如下是整篇文章的结构,所需阅读时间大约20min Spring简介 Spring框架由Rod Johnson开发,...
    逆风飞行1226阅读 4,423评论 0 15
  • 剩我一个人,一脸懵逼 同学都已在蠢蠢欲动为未来做打算了 跑步,骑行 才开学花销有点大,已经开始记账单,手里拿着窝窝...
    该用户没有设置昵称阅读 2,849评论 0 0
  • 时光匆匆,我的大学生活也不知不觉过了一年多,在这期间,很多感慨,很多故事。 作为一个农村的孩子考上大学其实是一件很...
    秋叶随风V阅读 3,570评论 0 6

友情链接更多精彩内容