How to add POJO to Spring context to enable injecting dependencies?

五迷三道 提交于 2019-12-11 01:12:27

问题


I have a class that would otherwise be a very generic POJO but I would like to inject a dependency in it because I would like to avoid passing that dependency as a (constructor) parameter:

//no managed context annotation because it's a simple POJO
public class QueuedBatch {

    //however, I would like to inject the context managed bean below
    @Autowired
    AsyncActionQueue asyncActionQueue;

Currently, no exception is thrown at deploy time but asyncActionQueue is null at runtime so I get a NullPointer when I hit the POJO.

How can I annotate my POJO to add it to the Spring managed context so that I can inject dependencies into it? AsyncActionQueue is a singleton and I would rather not be passing it to QueuedBatch as a (constructor) parameter.

This post is similar, except that I want to add my POJO into the managed context.


回答1:


As the comments suggested you have 2 ways of dealing with this

  1. Pass the AsyncActionQueue as a parameter in the constructor of QueuedBatch. This doesnt require Spring to know anything about QueuedBatch, but enforces the dependency to be provided when an instance of QueuedBatch is created.

  2. Annotate the QueuedBatch class with @Component. And ensure that the package which contains QueuedBatch is included in the component scan when initializing the spring context. In this way, it becomes a spring managed bean allowing AsyncActionQueue to be autowired into it. You may change the scope of QueuedBatch component based on your requirement.



来源:https://stackoverflow.com/questions/39353019/how-to-add-pojo-to-spring-context-to-enable-injecting-dependencies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!