开发者

Call different Service api's based on the entity object in spring framework

I am working on a web service application designed using spring framework, where I have different entity classes(ActivityA,ActivityB,ActivityC...) which inherit from a base class "activity"

Now I have written different service api's in service layer for the base class and all the child classes. (to name, ActivityService,ActivityAService,ActivityBService,ActivityCService..)

All the methods which operate similar for each activity are put in service api of base class(ActivityService) and rest in their respective services.

I generally know which object I am working on, and I call the respective service api. But in a particular case I have the activity object(d开发者_开发技巧on't know of which child class it is) and have to write a method which is different for all entity objects.

PROBLEM : Is there a way,I can call different service's based on the entity object I have.(the object I have is of entity, not service and I cant do any hard coding to get Service object)


But in a particular case I have the activity object(don't know of which child class it is) and have to write a method which is different for all entity objects.

Just make the base class abstract and define an abstract method that each sub class has to implement:

public abstract class ActivityService{
    public abstract Foo processEntity(Entity entity);
}

PROBLEM : Is there a way,I can call different service's based on the entity object I have.(the object I have is of entity, not service and I cant do any hard coding to to )

This is a situation you should try to avoid. Usually, you should only send an entity to a service that knows what to do with it, and not to a bunch of services, one of which is in charge. But what I'd do is use a dispatcher service that keeps a map of classes that the services are in charge of. It uses logic like this:

private Map<Class<? extends Entity>,
    Class<? extends ActivityService>> serviceMap =
        new ConcurrentHashMap<Class<? extends Entity>,
                              Class<? extends ActivityService>>();
private ApplicationContext context;
private ActivityService getServiceForEntity(Entity e){
    Class<? extends Entity> entityClass = e.getClass();
    Class<? extends ActivityService> serviceClass =
        serviceMap.get(entityClass);
    if(serviceClass==null){
        for(Map.Entry<Class<? extends Entity>,
                      Class<? extends ActivityService>> entry :
            serviceMap.entrySet()){
            if(entry.getKey().isAssignableFrom(entityClass)){
                serviceClass = entry.getValue();
                break;
            }
        }
        if(serviceClass==null){
            // throw a suitable exception
        }
        serviceMap.put(entityClass, serviceClass);
    }
    return context.getBean(serviceClass);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜