How to add POJO to Spring context to enable inject

2019-07-15 01:17发布

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条回答
相关推荐>>
2楼-- · 2019-07-15 02:08

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.

查看更多
登录 后发表回答