美文网首页
spring中Thread子类注入Service(bean)无效

spring中Thread子类注入Service(bean)无效

作者: writeanewworld | 来源:发表于2019-11-14 14:03 被阅读0次

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.启动三个线程


image.png

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


image.png

相关文章

网友评论

      本文标题:spring中Thread子类注入Service(bean)无效

      本文链接:https://www.haomeiwen.com/subject/fkrrictx.html