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

相关推荐
有个傻瓜4 小时前
分页 total 对不上、列表还少几条:MyBatis-Plus 一对多 LEFT JOIN 分页错乱复盘与四种写法实测
spring boot·sql优化·mybatis-plus·分页查询·踩坑复盘
考虑考虑5 小时前
JDK27结构化并发
java·后端·java ee
Cosolar7 小时前
监控指标全正常,订单接口从 80ms 涨到 4s 故障复盘
java·后端·面试
千寻技术帮15 小时前
微信小程序+Spring Boot 烘焙商城系统(附完整源码+数据库+部署文档)50053
数据库·spring boot·微信小程序·烘焙商城
会编程的吕洞宾16 小时前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
斯维赤16 小时前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
stormsha16 小时前
库存 5,10 个并发各买 1 件:为什么最后不剩 -5 件
java·数据库·mysql
RobinXYuan17 小时前
【Java 字节码探秘】02 ClassFile 骨架:十个字段
java·jvm·源码阅读
炸薯条!17 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
SimonKing18 小时前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员