ToHe
ToHe

Reputation: 147

How to inject Spring Bean in thread

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>">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

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 {

    //Exception
}

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!

Upvotes: 2

Views: 8668

Answers (1)

axtavt
axtavt

Reputation: 242686

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.

Upvotes: 1

Related Questions