-
May 19th, 2009, 03:36 PM
#1
How to inject bean in a class which extends Thread
Hi, I have a thread class, say Thread_A, which extends Thread class. This thead is created by:
Thread_A a = new Thread_A();
a.start();
So this is not an injection. However, in Thread_A, I'd like to start injecting spring managed beans.
@Configurable
Class Thread_A extends Thread{
@Autowired
private MyBean myBean;
void run(){
myBean.doSomething();
}
}
However, myBean is always null.I have tried different annotation such as @Service, @Component but none of them works.
Could you tell me what I did wrong?
-
May 20th, 2009, 02:11 AM
#2
Spring IoC usage assumes that you retrieve the beans with configured dependencies from the IoC container (application context). If you create the bean via 'new' operator, the framework has no chance to inject the dependencies (it's possible to exploit AOP programming to achieve resources injection with 'new' operator usage but that is advanced usage).
So, you should create the context and retrieve your thread bean from there instead of creating it via 'new'.
Also consider redesigning the class in order to make it not extend Thread but implement Runnable/Callable because that would bring much more flexibility and maintainability to your application.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules