Dyamically choose service implementation in Spring
dependency-injection, java, spring, spring-mvc
Solution
Assuming you need both implementations in production environment (if not - use Spring profiles to clearly split beans between environments). Simple approach would be:
interface DevService
{
void add(Device d);
String getName();
}
@Service("devServiceLocal")
class DevServiceLocalImpl implements DevService
{
void add(Device d) {...}
String getName() {return "local";}
}
class Controller
{
@Autowired
Collection<DevService> services;
void doSomethingWithService()
{
// TODO: Check type somehow
String servType = "local";
for(DevService s: services)
{
if(servType.equals(s.getName())
{
// Call service methods
break;
}
}
}
}
Problem
I am using spring 3.2 and would like to dynamically choose a service implementation in my controller depending on a condition. Consider I have an interface and two implementations as follows : ``` public interface DevService { public void add(Device device); } public class DevServiceImpl implements DevService { public void add(Device device) { } } public class RemoteDevServiceImpl implements DevService { public void add(Device device) { } } ``` So in my controller, depending on whether the action is to be executed on the local site or remote site, I need to either execute it locally or send a command to the remote site to execute it. Essentially the site on which the user clicks determines which service impl to call. Can anybody suggest a clean way to achieve this ?