|
From: Colin S. <col...@ex...> - 2003-11-18 17:08:56
|
I think I may be missing something, but I think it's desireable to be
able to create in an easy fashion, 'closures' which encapsulate getting
a bean from a bean factory.
Say you have an interface
interface MyInteface { ... whatever }
and you have a factory Interface
interface MyInterfaceFactory {
MyInterface getInstance();
}
And you have a user of the factory, who you'd rather have no knowledge
of Spring, which is why he's using the factory instead of calling
getBean himself:
class User {
MyInterfaceFactory _myfac;
public void setMyInterfaceFactory(MyInterfaceFactory myfac) { _myfac =
myfac; }
public void someMethod() {
// need a new instance of MyInterface to work with
MyInterface myint = _myfac.getInstance();
...
}
}
Now I have a bean factory
<beans>
<bean id="myinterface" singleton="false"
class="com.whatever.MyInterfaceImpl">
</bean>
<bean id="user" class="com.whatever.User">
<property name="myInterfaceFactory"><ref bean="xxxxxxxx"/></property>
</bean>
</beans>
now, as per the above, context.getBean("myinterface") is already a
factory for objects implementing MyInterface. But I don't want the User
object to know anything about contexts. And I'd rather not create an
actual object that implements MyInterfaceFactory. It seems like a waste,
since all I am doing here is trying to create a level of indirection,
and I already have a factory inside the context itself, and I may want
to use this approach in 30 different places, just to add a level of
indirection in creating new objects.
So what I think is needed is some variation of ProxyFactoryBean (but a
separate class), which given a target bean (which is itself a factory),
and a factory interface having a method with no args which returns a
certain type, creates on the fly a new class implementing the factory
interface, which will just use the target factory bean to actually
supply the instance. So the bean def above would become:
<beans>
<bean id="myinterface" singleton="false"
class="com.whatever.MyInterfaceImpl">
</bean>
<bean id="myinterface-factory" class="org.springframework.whatever.XXXX">
<property name="targetBean"><ref bean="xxxxxxxx"/></property>
<property
name="interface"><value>x.y.z.AFactoryInterface</value></property>
</bean>
<bean id="user" class="com.whatever.User">
<property name="myInterfaceFactory"><ref
bean="myinterface-factory"/></property>
</bean>
</beans>
Am I missing an existing way to do this? Is this worth adding to spring
as a convenience built-in, along the lines of TransactionProxyFactoryBean?
|