什么时候在Spring中使用javax.inject.Provider? [英] When to use javax.inject.Provider in Spring?

查看:1550
本文介绍了什么时候在Spring中使用javax.inject.Provider?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是很简单:

@Inject
private Provider<ProductService> productService;

产品服务可通过 productService.get() .get()将从每个调用的Spring上下文中解析实例。

The Product service is available through productService.get() and .get() will resolve the instance from the Spring context on each call.

但是我应该用吗在哪里?

But when should I use it? And where?

我的主要用例很简单:当我获得循环依赖性时,提供者有助于在运行时解析依赖关系。但是看起来有点随机,如果你把它放在只是wenn你不能创建你的上下文导致的循环依赖。

My main usecase is pretty simple: When I get circular dependencies the provider helps to resolve the dependency at runtime. But it looks a bit random if you throw it in just wenn you can't create your context caused by a circular dependency.

有没有关于供应商使用情况的已知模式?

Are there any known patterns about the usage of Providers?

推荐答案

此接口相当于 org.springframework.beans.factory.ObjectFactory< T> ,这是用于避免 BeanFactory.getBean()在查找原型实例时调用客户端代码。通常与 ObjectFactoryCreatingFactoryBean 一起使用,以获取由BeanFactory提供的原型bean。

This interface is equivalent to org.springframework.beans.factory.ObjectFactory<T> that is tipically used to avoid BeanFactory.getBean() calls in client code when looking for prototype instances. Often used with ObjectFactoryCreatingFactoryBean to get protoypes beans sourced by the BeanFactory.

示例来自 ObjectFactoryCreatingFactoryBean javadocs:

example from ObjectFactoryCreatingFactoryBean javadocs:

<beans>

   <!-- Prototype bean since we have state -->
   <bean id="myService" class="a.b.c.MyService" scope="prototype"/>

   <bean id="myServiceFactory"
       class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
     <property name="targetBeanName"><idref local="myService"/></property>
   </bean>

   <bean id="clientBean" class="a.b.c.MyClientBean">
     <property name="myServiceFactory" ref="myServiceFactory"/>
   </bean>

</beans>

使用提供商,您可以使用 ProviderCreatingFactoryBean

其他选项解决相同的问题,(使用继承而不是组合)是
查找方法注入

Other option to solve the same problem, (using inheritance instead composition) is the lookup method injection

这篇关于什么时候在Spring中使用javax.inject.Provider?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆