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);

相关推荐
Mr_pyx1 小时前
Spring AI 入门教程:Java开发者的AI应用捷径
java·人工智能·spring
Zephyr_02 小时前
Leedcode算法题
java·算法
苍煜2 小时前
Java开发IO零基础吃透:BIO、NIO、同步异步、阻塞非阻塞
java·python·nio
折哥的程序人生 · 物流技术专研2 小时前
Java面试85题图解版(一):基础核心篇
java·开发语言·后端·面试
AllData公司负责人3 小时前
通过Postgresql同步到Doris,全视角演示AllData数据中台核心功能效果,涵盖:数据入湖仓,数据同步,数据处理,数据服务,BI可视化驾驶舱
java·大数据·数据库·数据仓库·人工智能·python·postgresql
哆啦A梦15883 小时前
20, Springboot3+vue3实现前台轮播图和详情页的设计
javascript·数据库·spring boot·mybatis·vue3
Hello.Reader3 小时前
算法基础(十)——分治思想把大问题拆成小问题
java·开发语言·算法
一只大袋鼠3 小时前
JavaWeb四种文件上传方式(下篇)
java·开发语言·springmvc·javaweb
TE-茶叶蛋4 小时前
深入研究 yudao-framework 模块:Java 编程能力提升指南
java·开发语言
逻辑驱动的ken4 小时前
Java高频考点场景题24
java·开发语言·面试·职场和发展·求职招聘