什么时候在 Spring 中使用 javax.inject.Provider? [英] When to use javax.inject.Provider in Spring?
问题描述
它的作用很简单:
@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?
我的主要用例非常简单:当我获得循环依赖时,提供程序会在运行时帮助解决依赖关系.但是,如果您在因循环依赖而无法创建上下文时将其放入,则它看起来有点随机.
My main use case 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 when you can't create your context caused by a circular dependency.
是否有任何已知的 Provider 使用模式?
Are there any known patterns about the usage of Providers?
推荐答案
这个接口相当于org.springframework.beans.factory.ObjectFactory
,通常用来避免BeanFactory.getBean()
在寻找原型实例时调用客户端代码.通常与 ObjectFactoryCreatingFactoryBean
一起使用以获取由 BeanFactory
获取的原型 bean.
This interface is equivalent to org.springframework.beans.factory.ObjectFactory<T>
that is typically used to avoid BeanFactory.getBean()
calls in client code when looking for prototype instances. Often used with ObjectFactoryCreatingFactoryBean
to get prototypes 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>
使用 Providers
,您可以使用 ProviderCreatingFactoryBean
代替.
With Providers
, you can use the ProviderCreatingFactoryBean
instead.
解决相同问题的其他选项,(使用继承代替组合)是查找方法注入
Other option to solve the same problem, (using inheritance instead composition) is the lookup method injection
这篇关于什么时候在 Spring 中使用 javax.inject.Provider?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!