We face that issue in our project, and we solve it through a Factory-Like class. The client class -the one that needed the bean at runtime- had an instance of the factory, that was injected through Spring:
@Component
public class ImTheClient{
@Autowired
private ImTheFactory factory;
public void doSomething(
Parameters parameters) throws Exception{
IWantThis theInstance = factory.getInstance(parameters);
}
}
So, the IWantThis
instance depends on the runtime value of the parameters
parameter. The Factory implementation goes like this:
@Component
public class ImTheFactoryImpl implements
ImTheFactory {
@Autowired
private IWantThisBadly anInstance;
@Autowired
private IAlsoWantThis anotherInstance;
@Override
public IWantThis getInstance(Parameters parameters) {
if (parameters.equals(Parameters.THIS)) {
return anInstance;
}
if (parameters.equals(Parameters.THAT)) {
return anotherInstance;
}
return null;
}
}
So, the factory instance holds reference to both of the posible values of the IWantThis
class, being IWantThisBadly
and IAlsoWantThis
both implementations of IWantThis
.