• SpringBoot手动获取Bean


    SpringBoot手动获取Bean

    此事起因是用多线程编写定时任务,任务结束后有存储数据库的操作。我在线程的实现类里自动注入dao类,结果执行save操作报注入类实例空指针异常。

    Exception in thread "bd213f61a79f4436bf8f0bcd668a8e07" java.lang.NullPointerException: Cannot invoke "com.lhx.upgrade.repositories.UpgradeRecordRepository.save(Object)" because "this.recordRepository" is null

    看来Spring是不会给线程自动注入。

    找到一种手工从bean工厂获取依赖的办法:

    @Component
    public class BeanFactory implements ApplicationContextAware {
        private static ApplicationContext applicationContext = null;
    
        @Override
        public void setApplicationContext(ApplicationContext arg0) throws BeansException {
            // TODO Auto-generated method stub
            BeanFactory.applicationContext = arg0;
        }
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
        public static <T> T getBean(Class<T> clazz) {
            return getApplicationContext().getBean(clazz);
        }
    }
    

    在线程的run函数里添加下面代码即可

    UpgradeRecordRepository recordRepository = BeanFactory.getBean(UpgradeRecordRepository.class);
    recordRepository.save(record);
    
    敌人总是会在你最不想它出现的地方出现!
  • 相关阅读:
    hibernate4 使用及 新特性
    hibernate数据库配置
    Hibernate 插入,修改,删除,查询语句
    Hibernate之HQL总结
    简单编程题
    冒泡排序
    Accelerating Enum-Based Dictionaries with Generic EnumComparer
    本机自定义域名跳转
    ckeditor自己用的配置文件config.js
    RazorExtensions Templated Razor Delegates
  • 原文地址:https://www.cnblogs.com/longhx/p/15741114.html
Copyright © 2020-2023  润新知