1.背景简介
项目需求生成大量的测试数据。因此在本地写了个接口,可以启用n个线程来快速批量生成数据。
但是当在线程内注入service调用mapper方法时,报了空指针异常。
2.原因
因为spring本身默认Bean为单例模式来构建 ,也是非线程安全的,因此禁止了在Thread子类中的注入行为,因此在Thread中直接注入bean是注入不进来的。
3.解决方法1
构造函数外部引用
@RestController
@RequestMapping("/waw/one")
public class OneController {
@Resource
private OneService oneService;
/**
* 向表中批量插入数据
*/
@PostMapping(value = "/start")
public void startGenerate(Integer threadCount){
System.out.println("开始创建线程...线程数为:" + threadCount );
for(int i=0;i<threadCount;i++){
new ServiceUse(oneService).start();
}
System.out.println("生成数据结束...");
}
}
//在thread子类中是无法通过注入来使用一些方法的(bean是单例)//这里通过外部引入来使用service
class ServiceUse extends Thread{
private OneService oneService;
public ServiceUse(OneService oneService){
this.oneService = oneService;
}
@Override
public void run() {
oneService.startGenerateData(1000);
}
}
4.启动三个线程

5.每个线程持有一千条随机数据

网友评论