gpt4 book ai didi

java - Spring中动态选择服务实现

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:45 25 4
gpt4 key购买 nike

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

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) {
}
}

因此在我的 Controller 中,根据操作是在本地站点还是远程站点执行,我需要在本地执行它或向远程站点发送命令来执行它。本质上,用户点击的站点决定了调用哪个服务实现。有人可以建议一种干净的方法来实现这一目标吗?

最佳答案

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

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;
}
}
}
}

关于java - Spring中动态选择服务实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18091999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com