动态地选择Spring中的服务实现 [英] Dyamically choose service implementation in Spring

查看:191
本文介绍了动态地选择Spring中的服务实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用spring 3.2,并希望根据条件在我的控制器中动态选择服务实现。考虑我有一个接口和两个实现如下:

I am using spring 3.2 and would like to dynamically choose a service implementation in my controller depending on a condition. Consider I have an interface and two implementations as follows :

public interface DevService {
   public void add(Device device);
}

public class DevServiceImpl implements DevService {
    public void add(Device device) {
    }
}

public class RemoteDevServiceImpl implements DevService {
    public void add(Device device) {
    }
}

因此,在我的控制器中,根据是要在本地站点还是远程站点上执行操作,我需要在本地执行它或者向远程站点发送命令来执行它。基本上,用户点击的站点确定要调用的服务。任何人都可以建议一个干净的方法来实现这个目标吗?

So in my controller, depending on whether the action is to be executed on the local site or remote site, I need to either execute it locally or send a command to the remote site to execute it. Essentially the site on which the user clicks determines which service impl to call. Can anybody suggest a clean way to achieve this ?

推荐答案

假设您需要在生产环境中进行这两种实现(如果没有 - 请使用Spring配置文件在环境之间清楚地分割bean)。简单的方法是:

Assuming you need both implementations in production environment (if not - use Spring profiles to clearly split beans between environments). Simple approach would be:

interface DevService
{
   void add(Device d);
   String getName();
}

@Service("devServiceLocal")
class DevServiceLocalImpl implements DevService
{
   void add(Device d) {...}
   String getName() {return "local";}
}

class Controller
{
   @Autowired
   Collection<DevService> services;

   void doSomethingWithService()
   {
      // TODO: Check type somehow
      String servType = "local";
      for(DevService s: services)
      {
         if(servType.equals(s.getName())
         {
            // Call service methods
            break;
         }
      }
   }
}

这篇关于动态地选择Spring中的服务实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆