mercredi 11 mars 2015

What is the best approach to get injected beans with same interface using spring DI?

I created one factory to decide what best implementation should be returned, based in some conditional check.



// Factory
@Component
public class StoreServiceFactory {

@Autowired
private List<StoreService> storeServices;

public StoreService getService(){

if(some condition...){
// want to return specific implementation on storeServices map, but using @Qualifier os something else
storeServices.get(0)
}
}
}


//Service Implementations
@Service
@Qualifier("PublicStoreService")
public class PublicStoreService implements StoreService {

public getStoreBalanceScore(){
Do Stuff....
}
}

@Service
@Qualifier("PrivateStoreService")
public class PrivateStoreService implements StoreService {

public getStoreBalanceScore(){
Do Stuff....
}
}


// Controller
@Autowired
StoreServiceFactory storeServiceFactory;

@Override
public StoreData getStoreBalance(String storeId) {
StoreService storeService = storeServiceFactory.getService();
return simulationService.simulate(sellerId, simulation);
}


Is this approach good? If yes, how can i get my service from an elegant way? I would like to use only annotations, without configurations.


Aucun commentaire:

Enregistrer un commentaire