2种方式从springbean中获取bean实例

解决@Autowired获取不到bean实例的解决办法

1.PublicSqlMapper sqlMapper = ApplicationContextUtils.getBean(PublicSqlMapper.class);

复制代码
package com.admin.common.utils.bean;

import org.apache.commons.text.WordUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


/***
 * @author wangwei
 * @date 2025-09-10
 * 上下文获取bean
 * 使用场景:
 * 1.非 Spring 管理的类中使用 Spring Bean,当需要在普通 Java 类(未被@Component、@Service等注解标记的类)中使用 Spring 管理的 Bean 时,可以通过该工具类获取
 *2.静态方法中使用 Spring Bean:静态方法中使用 Spring Bean
 * 3.优先推荐使用依赖注入(@Autowired、@Resource等)的方式获取 Bean,只有在确实无法使用依赖注入时才考虑使用此类
 ***/

@Component
//类获取 Spring 的应用上下文(ApplicationContext)
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext context;

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

    /**
     * 返回 Spring 应用上下文
     *
     * @return
     */
    public static ApplicationContext getContext() {
        return context;
    }

    /***
     * getBean 根据 Bean 名称获取 Bean 实例
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

  /***
   * 根据 Bean 名称和类型获取指定类型的 Bean
   * @param beanName
   * @param requiredType
   * @param <T>
   * @return
   */
    public static <T> T getBean(String beanName, Class<T> requiredType) {
        return context.getBean(beanName, requiredType);
    }

    public static <T> T getBean(Class<T> requiredType) {
        String simpleName = requiredType.getSimpleName();
        String name = WordUtils.uncapitalize(simpleName);

        T obj = null;
        try {
            obj = getBean(name, requiredType);
        } catch (NoSuchBeanDefinitionException e) {
        }

        if (obj != null) {
            return obj;
        }

        return context.getBean(requiredType);
    }
}

SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);

相关推荐
狼爷1 天前
吃透 Java Function 接口,搞定 99% 的 Stream 场景
java·函数式编程
祎雪双十Gy1 天前
从 DataX 的配置加载说起:我用 FastJson2 做了一个轻量级动态配置管理库
java·后端
小锋java12341 天前
分享一套锋哥原创的SpringBoot4+Vue3宠物领养网站系统
java
考虑考虑1 天前
Java实现hmacsha1加密算法
java·后端·java ee
掉鱼的猫1 天前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·spring boot
plainGeekDev1 天前
广播接收器 → Flow + Lifecycle
android·java·kotlin
plainGeekDev1 天前
EventBus → SharedFlow
android·java·kotlin
带刺的坐椅1 天前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·springboot·web·solon
用户3721574261351 天前
Java 将一个 PPT 文档拆分为多个文件
java
人活一口气2 天前
Spring Boot与AIGC的完美结合:从零搭建智能内容生成平台
java·spring boot·aigc