• 工具类从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 getBean(Class requiredType) {
            return applicationContext.getBean(requiredType);
        }
    
        public static  T getBean(String name, Class 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 getType(String name) {
            return applicationContext.getType(name);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

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

     TaskRunKafkaLogService taskRunKafkaLogService = (TaskRunKafkaLogService) SpringContextUtils.getBean("taskRunKafkaLogServiceImpl");
    
    • 1
  • 相关阅读:
    【5G NR】3GPP常用协议整理
    用HTML+CSS做一个漂亮简单的音乐网站
    制造业仓库很乱,该如何有效的管理呢?
    【机器学习】李宏毅——Adversarial Attack(对抗攻击)
    iOS 借助定位实现“保活”策略
    数据结构与算法-树
    Python中Lambda用法
    使用VUE3.0版本搭建H5模板
    混合IT基础设施的安全挑战与缓解策略
    确定性执行
  • 原文地址:https://blog.csdn.net/weixin_40496191/article/details/136398075