无法将 bean 注入非 spring bean

Not able to inject a bean into a non-spring bean

有一种情况,我需要将一个 class 注入到非 spring bean class 中。

public class ProducerTask implements Runnable {                 --> This is not a component

     @Override
     public void run() {
          BBExecutor bbExecutor = new BBExecutor (codes);
                    bbExecutor .process(details);
     }

}

然后我的 class 是 BBExecutor

public class BBExecutor {    --> Since this class is used in the thread, it can't be injected using Autowired, because we used "New" keyword.

     @Autowired
     BBService bbService --> This is coming as null

}

注意:BBService被定义为一个组件。 我怎样才能得到这个 bbService 对象

首先,将 bean 注入 class 没有被 Spring 上下文处理的 bean 并不是一个好主意。您真的担心 class 可以由 Spring 管理吗?

当然,有一种方法可以从上下文中获取任何现有的 bean,但我不建议在您的情况下这样做。尝试考虑应用程序的整体架构。通常,这种情况都是一些基本的错误。

或者也许是这样。我想 ProducerTask 是由一些 Spring bean 创建的。

public class ProducerTask implements Runnable {                 --> This is not a component

    private BBService bbService;

    public ProducerTask(BBService bbService) {
        this.bbService = bbService;
    }

    @Override
    public void run() {
         BBExecutor bbExecutor = new BBExecutor (codes, bbService);
                bbExecutor .process(details);
    }
}


public class BBExecutor {    --> Since this class is used in the thread, it can't be injected using Autowired, because we used "New" keyword.

     private BBService bbService; 

     public BBExecutor(some parameters...., BBService bbService) {
         this.bbService = bbService;
     }

}