The way I would do this is by using a system called arbitrary-method-replacement.
Create a class that implements org.springframework.beans.factory.support.MethodReplacer
, this will force you to create a method like so
public Object reimplement(Object o, Method m, Object[] args) throws Throwable
The parameters mean the following:
- o - the bean instance you're replacing a method on
- m - the method meta we are replacing
- args - the method arguments supplied (if any)
So I would imagine your class to look something like the following
public BeanAUserHelper implements MethodReplacer {
public Object reimplement(Object o, Method m, Object[] args) throws Throwable {
if (some expression){
return beanA;
}
else {
return beanB;
}
}
}
In your bean configuration, you then instruct Spring to replace the getBeanX()
method on your BeanAUser
like so
<!-- this is the bean who needs to get a different instance -->
<bean id="beanAUser" class="a.b.c.BeanAUser">
<!-- arbitrary method replacement -->
<replaced-method name="getBeanX" replacer="beanAUserHelper"/>
</bean>
<!-- this is your 'dynamic bean getter' -->
<bean id="beanAUserHelper" class="a.b.c.BeanAUserHelper"/>
I hope I understood your problem correctly :)