Announcement Announcement Module
Collapse
No announcement yet.
How to inject bean in a class which extends Thread Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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?

  • #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.

    Comment

    Working...
    X