Multiple Service Implementation in Spring


Problem


In Spring projects, we are using dependency injection for Spring Component. Some unique cases we might want get more than one Spring Component. Sure thing we can fix problem with another solutions but for now this is the coolest solution i found.


Solution


For simulating this problem, let create FileStorageService interface.

Now we should create FileStorageService's implementations.



Lots of FileStorageService exists in our project so we can create FileStorageManager for manage that business. How can FileStorageManager get FileStorageService with constructor injection?


public FileStorageManagerImpl(FileStorageService fileStorageService)
{
 this.fileStorageService = fileStorageService;
}

Did you notice the problem in the code above? In this situation Spring can’t guess which FileStorageService u want. You can solve this problem Qualifier annotation but we don’t want that. So what we are gonna do is try to get List<FileStorageService> instead of FileStorageService with constructor injection.


Brainstorm


For right now we talk about for best cases. What about other cases? There may be other problems or other solutions but these are the ones that come to my mind.

What if only one Service configs set in application.properties file?

In this situation we can use `ConditionalOnProperty` annotation for hedge service without config.

What if Service config depends on more than one Boolean Value?

In this situation we can add boolean isBeanAlive() method to FileStorageService interface. We can filter FileStorageService by isBeanAlive() == true in FileStorageServiceImpl.uploadFile(File file) method.

What if one Service get error while running own action?

In this situation we have to guesswork for our business.

If we want multiple service for only backup then we can choose Main Service. If Main Service gets error then we can throw exception to user. We can choose priority of services with config.

If we want multiple service for getting resource each service then we can save error action in database. If get request comes to FileStorageServiceImpl, we check any error in database for that resource. If error is not exist for any service than we can call any of  FileStorageService. If there is error exist for request than we can call non-error service.


Related Article

Previous Post Next Post