Use run-time value to load concrete spring class (managed by trans manager)
Problem: I want to be able to use a run-time value to tell Spring which of my concrete classes (beans) to load for a given interface. I also need the bean to be managed by Spring's transaction manager (which includes being able to specify the transaction properties in the spring config file).
Details:
I have something like the following for business logic interface and concrete classes:
public interface IVehicleProcessor { ... }
public class VehicleCarProcessor implements IVehicleProcessor { ... }
public class VehicleTruckProcessor implements IVehicleProcessor { ... }
I want to be able to have the specific concrete class (VehicleCarProcessor, VehicleTruckProcessor) specified outside of my code (via Spring) and to be able to have these classes managed by Spring's transaction manager. The issue, though, is I want to be able to use a run-time value to select which concrete class to load - something I don't know how to do
Without using a run-time value, I have something like the following in my spring bean configuration file which hard-codes the concrete class (note the transaction manager support):
<bean id="VehicleProcessorTarget"
class="com.mycompany.myapp.bl.VehicleCarProcessor" > <-- here's where the concrete class for IVehicleProcessor is specified
<property name="dataSource" ref="DataSource" />
</bean>
<bean id="VehicleProcessor" class="org.springframework.transaction.interceptor .TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
<property name="target" ref="VehicleProcessorTarget"/>
<property name="proxyTargetClass" value="true"/>
<property name="transactionAttributes">
<props>
<prop key="update*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED, -Exception</prop>
</props>
</property>
</bean>
And I get the bean via something like the following:
public IVehicleProcessor getVehicleProcessor()
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config/spring/myspringbeans.xml");
IVehicleProcessor vehicleProcessor = (IVehicleProcessor) this.context.getBean("VehicleProcessor");
return vehicleProcessor;
}
The problem, again, is that I need to be able to specify the concrete class for my bean based on a run-time value and not have the selection 'hard-coded' in the config file, and I want to be able to still be able to have it managed by spring's transaction manager.
Logically, something like:
public IVehicleProcessor getVehicleProcessor(String vehicleType)
{
if (vehicleType.equals("Car"))
{
// For VehicleProcessorTarget, load com.mycompany.myapp.bl.VehicleCarProcessor
}
else if (vehicleType.equals("Truck"))
{
// For VehicleProcessorTarget, load com.mycompany.myapp.bl.VehicleTruckProcessor
}
}
Of course, if the above if-else can be instead be put into the spring config (with the vehicleType passed to spring), that would be optimal.
Any help?
Thanks,
Bill