工具类从spring里面获取对象

  1. 创建工具类

    /**

    • spring容器的相关方法,如根据名称获取spring实例
    • @author 天真热
    • @create 2022-04-28 9:55
    • @desc
      **/

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;

    @Component
    public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    复制代码
     @Override
     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         SpringContextUtils.applicationContext = applicationContext;
     }
    
     public static Object getBean(String name) {
         return applicationContext.getBean(name);
     }
    
     public static <T> T getBean(Class<T> requiredType) {
         return applicationContext.getBean(requiredType);
     }
    
     public static <T> T getBean(String name, Class<T> requiredType) {
         return applicationContext.getBean(name, requiredType);
     }
    
     public static boolean containsBean(String name) {
         return applicationContext.containsBean(name);
     }
    
     public static boolean isSingleton(String name) {
         return applicationContext.isSingleton(name);
     }
    
     public static Class<? extends Object> getType(String name) {
         return applicationContext.getType(name);
     }

    }

2.调用

ps:正常我们不指定类注入到spring的名称,默认都是使用"首字母小写的类名"作为名称

复制代码
 TaskRunKafkaLogService taskRunKafkaLogService = (TaskRunKafkaLogService) SpringContextUtils.getBean("taskRunKafkaLogServiceImpl");
相关推荐
都叫我大帅哥32 分钟前
深入浅出 Resilience4j:Java 微服务的“免疫系统”实战指南
java·spring cloud
程序员爱钓鱼35 分钟前
Go语言实战案例-判断一个数是否为质数
后端·google·go
程序员爱钓鱼40 分钟前
Go语言实战案例-读取本地文本文件内容
后端·google·go
Cao_Shixin攻城狮3 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
Dcs5 小时前
还在用 Arrays.hashCode?Java 自己也能写出更快的版本!
java
fouryears_234177 小时前
Spring,Spring Boot 和 Spring MVC 的关系以及区别
java·spring boot·spring·mvc
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
浮生带你学Java8 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展
板板正8 小时前
SpringAI——提示词(Prompt)、提示词模板(PromptTemplate)
java·spring boot·ai·prompt
板板正8 小时前
SpringAI——对话记忆
java·spring boot·ai