Question

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;
        }
    }
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top