Switch autowired services based on condition?

I'd like to have a delegator that can switch autowired services based on a string condition (I don't have any impact on that String).

How could I implement such a logic? I thought of a delegator class, but that introduces several problems: - I cannot inject multiple services of the same parent type - I would have all services injected and most of them are not used, as always only one service should be picked.

The services should as well get a PROTOTYPE scope.

How could I improve the following design?

@Service class AbstractService;
@Service class FirstService extends AbstractService;
@Service class SecondService extends AbstractService;
@Service class ThirdService extends AbstractService;
...

@Controller
class Delegator {
    @Autowired FirstService first;
    @Autowired SecondService second;
    @Autowired ThirdService third;

    public AbstractService delegate(String condition) {
        switch(String s) {
            case caseA: return FirstService; break;
            case caseX: return SecondService; break;
            case caseY: return ThirdService; break;
        }
    }
}

Answers


You should be able to do just this (assuming all services are singleton scoped):

class Delegator {
    @Autowired
    private Map<String, YourService> services;
}

to have Spring inject all the services by bean name (the String key) in the map.

Now if you really need to inject prototype-scoped services, have a look at this link for ideas.


You can inject a List of YourService into your delegator and decide in your delegate method which service to call.

Spring security is just one example where you you can find an implementation of (Authentication)Manager -> (Authentication)Provider pattern.

This one loops through all providers but thats easy to change if you have control of your code.


Need Your Help

I am getting NotFoundHttpException in RouteCollection.php line 161:

php laravel laravel-routing

I am getting this error when I run it at http://localhost/myproject/public/vendor

How to install Tomee in AWS ubuntu environment?

ubuntu amazon-web-services tomcat7 tomee

I want to install tomee on ubuntu AWS. I have installed JDK and its working fine with maven 3 is working and my Java -version give correct jdk details.