springboot通过ApplicationContextAware获取bean

本文介绍如何在SpringBoot应用中,通过实现ApplicationContextAware接口来便捷地获取ApplicationContext中的所有Bean,从而直接访问配置文件中定义的各个Bean对象。

 一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得 ApplicationContext 中的所有 bean。换句话说,就是这个类可以直接获取 Spring 配置文件中,所有有引用到的 Bean 对象

@Component
public class SpringContext implements ApplicationContextAware, DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(SpringContext.class);

    private static ApplicationContext applicationContext;

    /**
     * 获取存储在静态变量中的 ApplicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * 从静态变量 applicationContext 中获取 Bean,自动转型成所赋值对象的类型
     * @param name
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量 applicationContext 中获取 Bean,自动转型成所赋值对象的类型
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        assertContextInjected();
        return applicationContext.getBean(clazz);
    }

    /**
     * 实现 DisposableBean 接口,在 Context 关闭时清理静态变量
     * @throws Exception
     */
    public void destroy() throws Exception {
        logger.debug("清除 SpringContext 中的 ApplicationContext: {}", applicationContext);
        applicationContext = null;
    }

    /**
     * 实现 ApplicationContextAware 接口,注入 Context 到静态变量中
     * @param applicationContext
     * @throws BeansException
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContext.applicationContext = applicationContext;
    }

    /**
     * 断言 Context 已经注入
     */
    private static void assertContextInjected() {
        Validate.validState(applicationContext != null, "applicationContext 属性未注入,请在 spring-context.xml 配置中定义 SpringContext");
    }
}

还需要注入容器

在Spring Boot中,使用context获取bean有多种方法: 1. **通过名称获取Bean**:可以使用`getBean`方法通过Bean名称获取Bean。示例代码如下: ```java MyBean myBean = (MyBean) context.getBean("myBean"); ``` 这种方式需要进行强制类型转换,因为返回的是`Object`类型,需要将其转换为实际的Bean类型。 2. **通过类型获取Bean**:可以使用`getBean`方法通过Bean类型获取Bean。示例代码如下: ```java MyBean myBean = context.getBean(MyBean.class); ``` 这种方式不需要进行强制类型转换,因为方法会直接返回指定类型的Bean。 3. **通过名称和类型同时获取Bean**:如果存在多个符合条件的Bean,可以使用带有名称和类型参数的`getBean`方法来获取Bean。示例代码如下: ```java MyBean myBean = context.getBean("myBean", MyBean.class); ``` 这种方式既指定了Bean的名称,又指定了类型,能更精确地获取到所需的Bean。 要获取Spring Boot的`context`,可以通过实现`ApplicationContextAware`接口来实现,示例代码如下: ```java import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextProvider implements ApplicationContextAware { private static ApplicationContext context; public static ApplicationContext getApplicationContext() { return context; } @Override public void setApplicationContext(ApplicationContext ctx) { context = ctx; } } ``` 使用时,通过`ApplicationContextProvider.getApplicationContext()`即可获取到`context`,进而使用上述方法获取Bean。此外,也可以通过以下方式实现获取`context`和Bean: ```java import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringBeanUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringBeanUtil.applicationContext = applicationContext; } public Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } } ``` 通过`SpringBeanUtil`类可以方便地从`context`中获取Bean。还有另一种实现方式: ```java import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; @Configuration public class ApplicationContextHand implements ApplicationContextAware { private static ApplicationContext applicationContextHand; @Override public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext) throws BeansException { applicationContextHand = applicationContext; } public static Object getBean(Class c, String name) { return applicationContextHand.getBean(name, c); } } ``` 可以通过`ApplicationContextHand.getBean(Class c, String name)`方法获取指定名称和类型的Bean [^1][^2][^3][^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值