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
 
posted @ 2021-04-27 09:32  李悠然  阅读(1402)  评论(0编辑  收藏  举报