如何在 Spring 中使用自动装配的 bean 创建简单的工厂模式?

Tar*_*rek 5 java spring factory-method

我有一个具有 4 个非常相似方法的控制器,在远程服务器上调用 API 以对不同类型的用户执行不同的操作。这些 API 调用之间发生的变化只是端点和一些参数。

因此,这 4 个方法都使用非常相似的代码调用服务:它们从服务器获取令牌、设置参数、返回 API 的响应。由于稍后将添加更多操作,我决定使用工厂方法模式创建一个 ServiceFactory 并在服务上使用模板模式以避免代码重复。

我的问题是,为了让工厂自动装配服务,它需要与它们耦合,我必须对@Autowire每个实现进行耦合。有更好的解决方案吗?

这是我到目前为止的代码:

休息控制器

@RestController
public class ActionController {
  @Autowired
  private SsoService ssoService;

  // this is the factory
  @Autowired
  private ServiceFactory factory;

  @PostMapping("/action")
  public MyResponse performAction(@RequestBody MyRequest request, HttpServletRequest req) {
    // template code (error treatment not included)
    request.setOperator(ssoService.getOperator(req));
    request.setDate(LocalDateTime.now());
    return serviceFactory.getService(request).do();
  }
}
Run Code Online (Sandbox Code Playgroud)

服务工厂

@Component
public class ServiceFactory {

  @Autowired private ActivateUserService activateUserService;
  @Autowired private Action2UserType2Service anotherService;
  //etc

  public MyService getService(request) {
    if (Action.ACTIVATE.equals(request.getAction()) && UserType.USER.equals(request.getUserType()) {
      return activateUserService;
    }
    // etc
    return anotherService;
  }
}
Run Code Online (Sandbox Code Playgroud)

Service Base,实现 MyService 接口

public abstract class ServiceBase implements MyService {

  @Autowired private ApiService apiService;
  @Autowired private ActionRepository actionRepository;
  @Value("${api.path}") private String path;

  @Override
  public MyResponse do(MyRequest request) {
    String url = path + getEndpoint();
    String token = apiService.getToken();

    Map<String, String> params = getParams(request);
    // adds the common params to the hashmap

    HttpResult result = apiService.post(url, params); 
    if (result.getStatusCode() == 200) {
      // saves the performed action
      actionRepository.save(getAction());
    }
    // extracts the response from the HttpResult
    return response;
  }
}
Run Code Online (Sandbox Code Playgroud)

服务实现(有4个)

@Service
public class ActivateUserService extends ServiceBase {
  @Value("${api.user.activate}")
  private String endpoint;

  @Override
  public String getEndpoint() {
    return endpoint;
  }

  @Override
  public Map<String,String> getParams(MyRequest request) {
    Map<String, String> params = new HashMap<>();
    // adds custom params
    return params;
  }

  @Override
  public Action getAction() {
    return new Action().type(ActionType.ACTIVATED).userType(UserType.USER);
  }
}
Run Code Online (Sandbox Code Playgroud)

Jus*_*ano 11

您可以@Autowireda Listof MyService,这将创建List实现该MyService接口的所有 bean 的a 。然后你可以添加一个方法来MyService接受一个MyRequest对象并决定它是否可以处理该请求。然后,您可以过滤ListofMyService以找到MyService可以处理请求的第一个对象。

例如:

public interface MyService {

    public boolean canHandle(MyRequest request);

    // ...existing methods...
}

@Service
public class ActivateUserService extends ServiceBase {

    @Override
    public boolean canHandle(MyRequest request) {
        return Action.ACTIVATE.equals(request.getAction()) && UserType.USER.equals(request.getUserType());
    }

    // ...existing methods...
}

@Component
public class ServiceFactory {

    @Autowired
    private List<MyService> myServices;

    public Optional<MyService> getService(MyRequest request) {
        return myServices.stream()
            .filter(service -> service.canHandle(request))
            .findFirst();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,ServiceFactory上面的实现使用 Java 8+。如果 Java 8 或更高版本无法实现,您可以ServiceFactory通过以下方式实现该类:

@Component
public class ServiceFactory {

    @Autowired
    private List<MyService> myServices;

    public Optional<MyService> getService(MyRequest request) {

        for (MyService service: myServices) {
            if (service.canHandle(request)) {
                return Optional.of(service);
            }
        }

        return Optional.empty();
}
Run Code Online (Sandbox Code Playgroud)

有关使用@Autowiredwith 的更多信息List,请参阅按类型将 bean 自动装配到列表中


此解决方案的核心是将决定MyService实现是否可以处理 aMyRequestServiceFactory(外部客户端)的逻辑转移到MyService实现本身。