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

相关推荐
q***56382 分钟前
Spring容器初始化扩展点:ApplicationContextInitializer
java·后端·spring
q***51898 分钟前
SpringCloud系列教程:微服务的未来(十四)网关登录校验、自定义过滤器GlobalFilter、GatawayFilter
java·spring cloud·微服务
go__Ahead23 分钟前
【Java】线程池源码解析
java·juc
wyhwust31 分钟前
数组----插入一个数到有序数列中
java·数据结构·算法
专注于大数据技术栈35 分钟前
java学习--final
java·开发语言·学习
努力发光的程序员1 小时前
互联网大厂Java面试:从Spring Boot到微服务架构
spring boot·缓存·微服务·消息队列·rabbitmq·spring security·安全框架
天殇凉1 小时前
AC自动机学习笔记
java·笔记·学习
TechTrek2 小时前
Spring Boot 4.0正式发布了
java·spring boot·后端·spring boot 4.0
飞梦工作室2 小时前
企业级 Spring Boot 邮件系统开发指南:从基础到高可用架构设计
java·spring boot·后端
haiyu柠檬2 小时前
在Spring Boot中实现Azure的SSO+VUE3前端配置
java·spring boot·后端