简体   繁体   English

Spring @Autowired没有在新线程上工作

[英]Spring @Autowired not working on new thread

When I run TaskJob I am getting null pointer exception because Spring doesn't autowiring serviceJob service. 当我运行TaskJob时,我得到空指针异常,因为Spring没有自动装配serviceJob服务。 Is new thread causing this problem because Spring autowired mysqlService without any problem? 新线程是否导致此问题,因为Spring自动连接mysqlService没有任何问题?

public class TaskJob implements Runnable {
    @Autowired
    private ServiceJob serviceJob;

    String name;
    String source;

    public TaskJob(String name, String source) {
        this.name = name;
        this.source = source;
    }

    public void run() {
        serviceJob.run();
    }
}

@Service
public class ServiceJob extends BaseJob{

    @Autowired
    private MysqlService mysqlService;

    public void run(){
    ....
    }
}

@Service
public class MysqlService {
...
}

My applicationContext.xml; 我的applicationContext.xml;

<context:component-scan base-package="cm.*" /> 

And my classes are; 我的课程是;

cm.tasks.jobs.TaskJob
cm.jobs.ServiceJob
cm.services.MysqlService;

EDIT: TaskJob instanciated with; 编辑: TaskJob实例化;

TaskJob taskJob = new TaskJob(name, source);
Thread taskThread = new Thread(taskJob);
taskThread.start();

Spring only autowires components it creates. Spring只会自动装配它创建的组件。 You are calling new TaskJob(), Spring doesn't know about this object so no autowiring will take place. 你正在调用新的TaskJob(),Spring不知道这个对象所以不会发生自动装配。

As a workaround you can call the application context directly. 作为一种解决方法,您可以直接调用应用程序上下文。 Firstly get a handle on the application context. 首先了解应用程序上下文。 This can be done by adding @Autowire for the application context itself. 这可以通过为应用程序上下文本身添加@Autowire来完成。

@Autowired
private ApplicationContext applicationContext;

When you create TaskJob, ask the app context to do your auto-wiring. 创建TaskJob时,请询问应用程序上下文以进行自动连接。

TaskJob taskJob = new TaskJob(name, source);
applicationContext.getAutowireCapableBeanFactory().autowireBean(taskJob);

Additionally if you have any @PostConstruct annotated methods you need triggering you can call initializeBean() 另外,如果你有任何@PostConstruct注释方法需要触发,你可以调用initializeBean()

applicationContext.getAutowireCapableBeanFactory().initializeBean(taskJob, null);

Your TaskJob is instantiated wihh "new" operator which means the object created is not a spring bean. 你的TaskJob是用“new”操作符实例化的,这意味着创建的对象不是spring bean。 So you will have to write code to create object for the property (ServiceJob) with the new operator. 因此,您必须编写代码以使用new运算符为属性(ServiceJob)创建对象。

While using Spring spring framework Service objects are not created like this. 使用Spring spring框架时,不会像这样创建Service对象。 Kindly use getBean method of Applicationcontext. 请使用Applicationcontext的getBean方法。 Please see here 请看这里

请尝试这种类型

<context:component-scan base-package="cm.*,cm.tasks.jobs" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM