zoukankan      html  css  js  c++  java
  • Java线程调用DAO、Servic报出空指针异常

    项目中用到了多线程,但是线程异步操作时无法调用Service层和Dao层的函数,进行数据库的读取,然后就想办法如何往异步线程中注入Service和Dao层的bean。

    一直调试测试了很多

    1. 编写一个工具类作为从Spring中获取bean,注意 如果是通过@注解实现的一定要加Configuration这个注解,否则抱出context的空指针异常错误。

    package com.arm.config;

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.context.annotation.Configuration;

    /**
    * @Author hett
    * @Date 2021/4/27 9:07
    **/
    @Configuration
    public class AllBeanService implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    AllBeanService.context = applicationContext;
    }

    public static Object getBean(String className){
    if (context==null)
    return null;
    else
    return context.getBean(className);
    }
    public static <T> T getBean(Class<T> type) {
    return context.getBean(type);
    }
    public static ApplicationContext getApplicationContext(){
    return context;
    }
    }


    2. 在线程中使用工具类
    dataAnalyService= (DataAnalyService) AllBeanService.getBean("dataAnalyService");

    注意:("dataAnalyService") 这个名字与定义@service保持一致
    /**
    * @Author hett
    * @Date 2021/4/26 15:14
    **/
    @Service(value = "dataAnalyService")
    public class DataAnalyService {



    经过多次调试终于完成了,特此分享这个bug
     
  • 相关阅读:
    网络性能评估
    HTML5 historyState pushState、replaceState
    pre换行段落间距
    2、hibernate七步走完成增删改查
    8.多线程和Socket通信
    7..使用反射动态创建数组和访问数组
    5. Java反射机制
    11、触发器
    10.程序包
    9.函数
  • 原文地址:https://www.cnblogs.com/youran-he/p/14707552.html
Copyright © 2011-2022 走看看