Spring在多线程中使用bean注入

在开发多线程功能模块时,想使用serviceImplement实现某一具体功能;

原来是这样写:

public class MyThread2 implements Runnable { // 实现Runnable接口,作为线程的实现类

    private Integer userId;
    private FollowService followService;
    private UserService userService;


    public MyThread2( Integer userId) {
        this.userId = userId;
        this.userService = new UserServiceImpl();

    }

    @Override
    public void run() {  // 覆写run()方法,作为线程 的操作主体

    #使用userService的业务代码
    #userService.select();
    }


}

但是报错UserService空指针;

后来把bean作为构建函数传进去就解决了;

public MyThread2( Integer userId,UserService userService) {
        this.userId = userId;
        this.userService = userService;

    }


#在其他类中使用线程的地方如下:

public class A{

    MyThread2 myThread = new MyThread2(userId,userService);

    #userService是一个bean

    executor.execute(myThread);

    #executor是线程池
}

问题解决。

你可能感兴趣的:(Java学习,spring,java)