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

相关推荐
皮皮林5518 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河8 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程11 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅12 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者13 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺13 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart15 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP16 小时前
MyBatis-mybatis入门与增删改查
java
孟陬19 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端