利用静态方法获取spring的bean实例

 更新时间:2025年11月10日 09:27:08   作者:水煮鱼又失败了  
文章介绍了如何在Spring框架中通过工具类的静态方法获取Spring命名空间中的bean,思路包括定义bean并实现ApplicationContextAware接口,然后在代码中执行特定代码获取bean,扩展部分详细讲解了加载原理和注意事项

1 场景

spring命名空间中的bean,正常情况下可以使用@Autoware注解加在成员变量上注入,注入成功的前提是注入的对象必须已经是spring命名空间中的bean才可以。

当前有一种需求:通过工具类的静态方法,获取spring中的bean

2 思路

(1)定义bean

(2)bean实现ApplicationContextAware接口

3 代码

3.1 定义bean

/**
 * spring上下文句柄
 */
public class SpringContextHolder implements ApplicationContextAware {
    /**
     * spring上下文
     */
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext=applicationContext;
    }
    
    /**
     * 获取spring上下文
     * @return
     */
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }
    
    /**
     * 获取bean
     * @param name  bean名称
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name){
        if(applicationContext==null){
            return null;
        }
        return (T) applicationContext.getBean(name);
    }
    
    /**
     * 获取bean
     * @param requiredType bean类型
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> requiredType){
        if(applicationContext==null){
            return null;
        }
        return applicationContext.getBean(requiredType);
    }
    
    /**
     * 获取bean
     * @param name  bean名称
     * @param requiredType  bean类型
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> requiredType){
        if(applicationContext==null){
            return null;
        }
        return applicationContext.getBean(name,requiredType);
    }
}

3.2 注册bean

spring配置文件中,加载的xml最前面定义上述bean:

<!-- spring上下文句柄 -->
<bean id="springContextHolder" class="com.sa.demo.spring.context.SpringContextHolder"/>

3.3 使用

在java代码的任何一个地方执行下面代码,可以获取spring中的bean:

SpringContextHolder.getBean("xxxxxx");
SpringContextHolder.getBean("XXX.class")
SpringContextHolder.getBean("xxxxxx","XXX.class")

获取spring中的命名空间:

ApplicationContext applicationContext=SpringContextHolder.getApplicationContext();

4 扩展

4.1 源码讲解

加载原理:

实现的接口ApplicationContextAware中的方法定义如下:

/**
 * Set the ApplicationContext that this object runs in.
 * Normally this call will be used to initialize the object.
 * <p>Invoked after population of normal bean properties but before an init callback such
 * as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}
 * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
 * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
 * {@link MessageSourceAware}, if applicable.
 * @param applicationContext the ApplicationContext object to be used by this object
 * @throws ApplicationContextException in case of context initialization errors
 * @throws BeansException if thrown by application context methods
 * @see org.springframework.beans.factory.BeanInitializationException
 */
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

翻译如下:

设置运行该对象的ApplicationContext。
通常这个调用将用于初始化对象。
在填充普通bean属性之后,在init回调之前调用

表示实现此接口的bean,将在填充bean属性之后bean的init回调方法之前,调用此方法。方法的参数为spring的命名空间ApplicationContext

bean实现此接口后,会被调用相应方法,取决于以下源码:

方法路径:

org.springframework.context.support.ApplicationContextAwareProcessor#postProcessBeforeInitialization

org.springframework.context.support.ApplicationContextAwareProcessor#invokeAwareInterfaces

对应方法如下:

private void invokeAwareInterfaces(Object bean) {
    if (bean instanceof EnvironmentAware) {
        ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
    }
    if (bean instanceof EmbeddedValueResolverAware) {
        ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
    }
    if (bean instanceof ResourceLoaderAware) {
        ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
    }
    if (bean instanceof ApplicationEventPublisherAware) {
        ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
    }
    if (bean instanceof MessageSourceAware) {
        ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
    }
    if (bean instanceof ApplicationContextAware) {
        ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
    }
}

相应扩展部分:

当spring中注册的bean实现了如下接口:

EnvironmentAware
EmbeddedValueResolverAware
ResourceLoaderAware
ApplicationEventPublisherAware
MessageSourceAware
ApplicationContextAware

均会执行上述代码中对应的实现方法。

4.2 注意事项

(1)此类bean的定义,需在spring最前面定义。

(2)实现了接口ApplicationContextAware的bean,只能获取此bean所定义的spring命名空间。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • SpringBoot3匹配Mybatis3的错误与解决方案

    SpringBoot3匹配Mybatis3的错误与解决方案

    文章指出SpringBoot3与MyBatis3兼容性问题,因未更新MyBatis-Plus依赖至SpringBoot3专用坐标,导致类冲突,解决方案是替换pom中的依赖为`mybatis-plus-spring-boot3-starter:3.5.12`,并排除旧版本核心库,确保版本一致性
    2025-08-08
  • Kotlin 中安全地处理可空类型的方式

    Kotlin 中安全地处理可空类型的方式

    在 Kotlin 中,可空类型(如String?)是语言设计的核心特性之一,旨在从编译时避免 NullPointerException(NPE),这篇文章主要介绍了Kotlin 中该如何安全地处理可空类型,需要的朋友可以参考下
    2025-05-05
  • SpringBoot监视器的具体使用

    SpringBoot监视器的具体使用

    Spring Boot监视器是一个用于监控和管理Spring Boot应用程序的工具集,本文就来介绍一下SpringBoot监视器的具体使用,感兴趣的可以了解一下
    2025-01-01
  • Java实现二进制与十进制之间互相转换的完整代码

    Java实现二进制与十进制之间互相转换的完整代码

    在编程中,数制转换是一个非常常见的需求,Java 作为一种高级语言,提供了便捷的方法来实现 二进制和 十进制之间的转换,本文将介绍 Java 中二进制与十进制互转的原理与实现方式,并附上完整代码示例,
    ,需要的朋友可以参考下
    2025-08-08
  • SpringBoot Mybatis动态数据源切换方案实现过程

    SpringBoot Mybatis动态数据源切换方案实现过程

    这篇文章主要介绍了SpringBoot+Mybatis实现动态数据源切换方案过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • 详解Spring多数据源如何切换

    详解Spring多数据源如何切换

    这篇文章主要介绍了spring多数据源的如何切换,由于是spring项目,可以借助 spring 的DataSource 对象去管理,大体思路是创建一个类实现该接口,替换spring原有的DataSource 对象,文中有详细的代码示例供大家参考,需要的朋友可以参考下
    2024-06-06
  • Spring内部bean和级联属性用法详解

    Spring内部bean和级联属性用法详解

    这篇文章主要介绍了Java内部bean和级联属性用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • Java解析JSON的六大工具介绍与对比

    Java解析JSON的六大工具介绍与对比

    在 Java 开发中,解析 JSON 是一个非常常见的需求,不管是和前端交互、调用第三方接口,还是处理配置文件,本文总结了6种主流的 JSON 解析方法,希望对大家有所帮助
    2025-01-01
  • Effective Java 在工作中的应用总结

    Effective Java 在工作中的应用总结

    《Effective Java》是一本经典的 Java 学习宝典,值得每位 Java 开发者阅读。下面文章即是将书中和平日工作较密切的知识点做了部分总结,需要的朋友可以参考下
    2021-09-09
  • Java处理时间格式CST和GMT转换方法示例

    Java处理时间格式CST和GMT转换方法示例

    这篇文章主要给大家介绍了关于Java处理时间格式CST和GMT转换方法的相关资料,相信很多小伙伴在时间格式转换的时候非常头疼,文中通过代码示例介绍的非常详细,需要的朋友可以参考下
    2023-09-09

最新评论