最近我遇到了这个需求,我们有一个 Foo bean 和一个 Bar bean;两者都是单例,Bar 需要注入到 Foo 中。
但是,Bar 是资源/内存的重量级 bean,因此我们需要将其实例化延迟到 Foo 实际调用它的方法的地步。问题是,Foo 必须急切地实例化。那么有哪些不同的方法呢?
我在下面的答案中分享了我的解决方案。学习任何其他方法都会很棒。
最近我遇到了这个需求,我们有一个 Foo bean 和一个 Bar bean;两者都是单例,Bar 需要注入到 Foo 中。
但是,Bar 是资源/内存的重量级 bean,因此我们需要将其实例化延迟到 Foo 实际调用它的方法的地步。问题是,Foo 必须急切地实例化。那么有哪些不同的方法呢?
我在下面的答案中分享了我的解决方案。学习任何其他方法都会很棒。
本质上,这就是我所做的:
1)Bar
懒惰地实例化,
2)使用aLazyInitTargetSource
并将其指向上面的bean,
3)使用指向上面目标源的`ProxyFactoryBean',
4)Foo
热切实例化并将上面的代理注入其中。
此解决方案比使用lookup-method
解决方案更冗长、更复杂。然而lookup-method
,解决方案很难进行单元测试,我觉得与其他解决方案相比,它与 Spring 的耦合更紧密。
以下是配置:
<bean id="barTarget" class="bar.Bar" lazy-init="true">
<constructor-arg value="423" />
</bean>
<bean id="singletonTargetSource" class="org.springframework.aop.target.LazyInitTargetSource">
<property name="targetBeanName" value="barTarget" />
</bean>
<bean id="bar" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="targetSource" ref="singletonTargetSource" />
</bean>
<bean id="foo" class="foo.Foo">
<property name="bar" ref="bar" />
</bean>