无法将bean注入非spring bean

时间:2019-12-12 10:37:41

标签: spring autowired

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

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

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

}

然后我的班级是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对象

1 个答案:

答案 0 :(得分:1)

首先,将bean注入到Spring上下文未处理的类中并不是一个好主意。您真的有一些担心要让此类在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;
     }

}
相关问题