问题描述
我有一个否则会是非常普通的POJO的类,但我想在其中注入一个依赖项,因为我想避免将该依赖项作为(构造函数)参数传递:
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;
当前,在部署时不会引发任何异常,但是在运行时asyncActionQueue
为null,因此当我按下POJO时会得到一个NullPointer
.
Currently, no exception is thrown at deploy time but asyncActionQueue
is null at runtime so I get a NullPointer
when I hit the POJO.
如何注释我的POJO以将其添加到Spring托管上下文中,以便可以将依赖项注入其中? AsyncActionQueue
是单例,我不希望将其作为(构造函数)参数传递给QueuedBatch
.
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.
这篇文章相似,除了我想将我的POJO添加到托管上下文中.
This post is similar, except that I want to add my POJO into the managed context.
推荐答案
正如评论所建议的,您有两种处理方式
As the comments suggested you have 2 ways of dealing with this
-
在QueuedBatch的构造函数中将AsyncActionQueue作为参数传递.不需要Spring知道有关QueuedBatch的任何信息,但是可以强制创建QueuedBatch实例时提供依赖项.
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.
用@Component注释QueuedBatch类.并确保在初始化spring上下文时在组件扫描中包含包含QueuedBatch的包.通过这种方式,它变成了一个弹簧管理的bean,允许将AsyncActionQueue自动连接到其中.您可以根据需要更改QueuedBatch组件的范围.
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.
这篇关于如何将POJO添加到Spring上下文中以启用注入依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!