Spring - Access a Service interface programmatically

2018-04-19 spring

i have several interfaces which extend a single interface.

I need to add, during a @PostCostruct method, these interfaces to a Map.

The problem is that i need to retrieve the @Service class name from the DB and i don't know ho to put the interface in the map...

I'll try to explain it better

I have a general service interface

public interface IVehicleServiceGeneral{

//methods...
}

then i have several interfaces which extend the general one.

public interface IService1 extends IVehicleServiceGeneral{
}

public interface IService2 extends IVehicleServiceGeneral{
}

the concrete implementations of these classes are annotated with @Service("service1Name"), @Service("service2Name") and so on...

Then from the DB i retrieve my Suppliers

public class Supplier {

private long id;

private String serviceName;

//getters and setters
}

Finally i need to create the map, because i need to access the implementations at runtime based on the Supplier, i created a ContextAware class to get my beans by name, but the interfaces are not beans... I also tried to put the @Qualifier on the interface, but obviously it does not work... How can I put the interface in the map?

@PostConstruct
    private void createServiceMap(){

        serviceMap = new HashMap<OBUSupplier, IVehicleServiceGeneral>();
        List<Supplier> suppliers = supplierService.findAll();
        for(Supplier s : suppliers) {
            serviceMap.put(s, contextAware.getBean(s.getServiceName()));

        }

    }

Answers

You can create IVehicleServiceGeneral instance map like this:

class SomeClass {
   Map vehicleServiceGeneralInstanceMap = new HashMap();

   SomeClass(Set<IVehicleServiceGeneral> instances) {
      instances.forEach(i -> vehicleServiceGeneralInstanceMap.put(i.getServiceName(), i));
   }    


   private void createServiceMap() {
       Map serviceMap = new HashMap<OBUSupplier, IVehicleServiceGeneral>();
       List<Supplier> suppliers = supplierService.findAll();
       for(Supplier s : suppliers) {
           serviceMap.put(s, vehicleServiceGeneralInstanceMap.get(s.getServiceName()));

   }
}

The only thing you require is IVehicleServiceGeneral#getServiceName which your Service1, 2 need to override with proper names that present in DB.

Related