简体   繁体   English

如何动态注入spring bean(原型作用域)

[英]How to inject spring bean (prototype scope) dynamically

I'm using Spring 3.1.1 and in my business logic, I have a loop which requires a new instance of a spring bean (prototype scope) for each iteration. 我使用的是Spring 3.1.1,在我的业务逻辑中,我有一个循环,每次循环都需要一个新的Spring bean实例(原型作用域)。

What is the best method to do this? 最好的方法是什么? Must I create my own BeanFactory class which I can inject once into my class, and call upon it every time to produce the bean upon request? 我是否必须创建自己的BeanFactory类,可以将其一次注入到我的类中,然后每次都调用它以根据请求生成Bean? When looking at the Spring 3 docs , it seems to imply that I should use ApplicationContext instead. 在查看Spring 3文档时 ,似乎暗示我应该改用ApplicationContext。 However, using ApplicationContext makes my code Spring dependent. 但是,使用ApplicationContext使我的代码依赖于Spring。

What is the best method for something like this? 像这样的最佳方法是什么? Does Spring already provide a factory of sorts that I can leverage? Spring是否已经提供了我可以利用的各种工厂?

ApplicationContext is the factory. ApplicationContext 工厂。 You don't have to inject it into your class; 您不必将其注入课堂。 you instantiate one and use it to create the beans and wire up their dependencies. 您实例化一个,并用它来创建bean并连接它们的依赖关系。

I don't understand the comment "using ApplicationContext makes my code Spring dependent." 我不理解“使用ApplicationContext使我的代码依赖Spring”这一说法。 Yes, it does. 是的,它确实。 Do you think DI is worth it or not? 您认为DI值得吗?

I think you should go with spring. 我认为你应该和春天一起去。 Spring facilitates your need. 春天可以满足您的需求。 You can use a method to lookup bean of specific type from application context. 您可以使用一种方法从应用程序上下文中查找特定类型的Bean。 So if you make that bean to be prototype. 因此,如果您使该bean成为原型。 then when you call this special method, you will be returned with a new instance of the bean you want. 然后,当您调用此特殊方法时,将返回您想要的bean的新实例。

You will find it indetails here! 您将在这里找到它的详细信息!

您可以使用自定义范围并使注入Bean代理,并在自定义范围Bean上侦听一些可以注入基础代理Bean的动态事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM