Spring @Autowired在新线程上不起作用 [英] Spring @Autowired not working on new thread

查看:452
本文介绍了Spring @Autowired在新线程上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行TaskJob时,我得到了空指针异常,因为Spring不会自动装配serviceJob服务.是新线程导致此问题,因为Spring自动连接mysqlService没问题吗?

When I run TaskJob I am getting null pointer exception because Spring doesn't autowiring serviceJob service. Is new thread causing this problem because Spring autowired mysqlService without any problem?

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 {
...
}

我的applicationContext.xml;

My applicationContext.xml;

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

我的课是;

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

实例化了TaskJob;

TaskJob instanciated with;

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

推荐答案

Spring仅自动装配其创建的组件.您正在调用新的TaskJob(),Spring对该对象一无所知,因此不会进行自动装配.

Spring only autowires components it creates. You are calling new TaskJob(), Spring doesn't know about this object so no autowiring will take place.

作为解决方法,您可以直接调用应用程序上下文.首先获取应用程序上下文的句柄.这可以通过为应用程序上下文本身添加@Autowire来完成.

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.

@Autowired
private ApplicationContext applicationContext;

创建TaskJob时,要求应用程序上下文进行自动装配.

When you create TaskJob, ask the app context to do your auto-wiring.

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

另外,如果您有任何需要注释的@PostConstruct带注释的方法,则可以调用initializeBean()

Additionally if you have any @PostConstruct annotated methods you need triggering you can call initializeBean()

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

这篇关于Spring @Autowired在新线程上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆