需要为不同的api调用相同的控制器方法

问题描述 投票:1回答:1

我有2个API

1. localhost:8080/myservice/foo/1/0/updatesStatus
2. localhost:8080/myservice/bar/1/0/updatesStatus

我不允许每个API具有不同的控制器。因此,两个API都指向我可以进行if-else检查的相同控制器方法,但是代码看起来非常糟糕,有没有更好的方法来处理此问题。

@PostMapping(value = UPDATE_STATUS_API_PATH)
public Response updateStatus(@PathVariable("group") String group , @RequestBody UpdateStatusRequest updateStatusRequest, HttpServletRequest request) {
        try {
            if(APIUrl.FOO_GROUP.equals(group)){
               //code spefic to foo
            }
            else{
              //code spefic to bar
            }
            //common code
}

也必须在服务层上执行相同的条件检查。有没有什么方法可以避免这种条件检查而无需单独的控制器方法。

java rest spring-boot design-patterns code-cleanup
1个回答
1
投票

我能想到这一点。

创建服务接口。

public interface UpdateService {
    void updateStatus(UpdateStatusRequest updateStatusRequest);
}

然后您创建不同的实现。

public class FooUpdateService implements UpdateService  {
    void updateStatus(UpdateStatusRequest updateStatusRequest) {
        // foo specific logic
    }
}
public class BarUpdateService implements UpdateService  {
    void updateStatus(UpdateStatusRequest updateStatusRequest) {
        // Bar specific logic
    }
}

创建UpdateServiceFactory

public class UpdateServiceFactory {
    @Autowired
    private UpdateService fooUpdateService;

    @Autowired
    private UpdateService fooUpdateService;

    public UpdateService getUpdateService(String group) {
        // Move the if-else logic here
        if(APIUrl.FOO_GROUP.equals(group)){
               return fooUpdateService;
            }
            else{
              //code spefic to bar
              return barUpdateService;
            }
    }
}

控制器:

@PostMapping(value = UPDATE_STATUS_API_PATH)
public Response updateStatus(@PathVariable("group") String group , @RequestBody UpdateStatusRequest updateStatusRequest, HttpServletRequest request) {
        updateServiceFactory.getUpdateService(group).updateStatus(updateStatusRequest);
            //common code
}
© www.soinside.com 2019 - 2025. All rights reserved.