Take the 2-minute tour ×

I have a running Spring 3 web application. All the beans are correctly injected and everything is working as it should (all web service calls are working properly).

While expanding the application I needed to add threads that can be started & stopped via a web service.

In the thread I need to inject some Spring beans. These beens are services (annotated with @Service). In my applicationContext the beans are detected via a component scan:

<context:component-scan base-package="<package>">

But when I try to inject the beans (using @Resource) in the thread they are always 'null' (Spring doesn't inject them). The thread is started but fails while initializing.

I also tried injecting them by loading the applicationContext in code: (application context is located in 'src/main/resources')

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:*applicationContext.xml");

if(applicationContext.containsBean("BeanName")) {

        beanObject = (BeanClass) applicationContext.getBean("BeanName");

} else {


Does anyone have any idea how to inject the beans in the thread? Or isn't it possible to inject beans in a thread?

Thanks in Advance!

share|improve this question
Possible duplicate. Based on this answer, your custom class is extending Thread. –  nobeh Apr 13 '12 at 16:07

1 Answer 1

It would be better to separate business logic (the code that depends on your services) from the infrastructure code that manages threads.

For example, you can declare a bean that implements Runnable for your business logic and then use it when you need to start a Thread.

However, starting Threads manually is not a good practice as well. It would be better to use thread pools instead. Actually, Spring provides some built-in support for thread pools and asynchronous execution, so that you can leverage it, see 25. Task Execution and Scheduling.

share|improve this answer

Your Answer


