SpringBoot--静态获得Bean的工具类(基于ApplicationContext)

原文网址:SpringBoot--静态获得Bean的工具类(基于ApplicationContext)_IT利刃出鞘的博客-CSDN博客

简介

说明

        本文提供一个静态获得Bean的工具类。

        可以通过本工具类静态获取ApplicationContext,从而进一步使用ApplicationContext进行处理,比如:从容器中获取bean。

优点

        方便快捷,调用者直接使用静态方法即可,调用者无需自己再去实现ApplicationContextAware接口。

相关网址

Spring(SpringBoot)--ApplicationContext--使用/教程/原理_IT利刃出鞘的博客-CSDN博客

代码

package com.knife.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext context;

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        ApplicationContextHolder.context = context;
    }

    public static ApplicationContext getContext() {
        return context;
    }
}  

用法

  • 根据class获得bean(常用)
    • Xxx xxx = ApplicationContextHolder.getContext().getBean(Xxx.class);
  • 根据名字获得代理后的bean(常用)
    • Xxx xxx = ApplicationContextHolder.getContext().getBean("userService");
  • 根据名字获得未代理的bean(即FactoryBean)(不常用)
    • Xxx xxx = ApplicationContextHolder.getContext().getBean("&userService");

猜你喜欢

转载自blog.csdn.net/feiying0canglang/article/details/126679536
今日推荐