工具类从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");
相关推荐
瑞克-桑切斯8 分钟前
7、MySQL 慢查询排查与优化实战指南
java·服务器·数据库
考虑考虑1 小时前
Posrgresql恢复.backup文件
数据库·后端·postgresql
无奈何杨1 小时前
风控决策系统决策流,策略模式,权重、顺序、投票、最坏
后端
Patrick_Wilson3 小时前
Go 为什么需要 defer?从函数怎么收尾说起
后端·go·编程语言
苏三说技术3 小时前
DeepSeek Harness入驻B站,评论区被干成了大型插件集市!
后端
橙序员小站3 小时前
我一句话让 AI 把公众号工作台搭完了:部署实测记录
后端
Patrick_Wilson3 小时前
从文本输出理解 Go 方法与接口
后端·go·编程语言
Flynn Liang4 小时前
AI 应用的安全红线:Spring AI 下的 Prompt 注入防护、PII 脱敏、输出审计与密钥管理
人工智能·安全·spring·数据泄露·springai·prompt注入
QCoding4 小时前
企业级Agent Evaluation实战:Agent能跑就能上线?AI Agent到底怎么测?
后端·spring
苍何4 小时前
让 WorkBuddy 操控浏览器,干活有点猛啊1
后端