Spring MVC 使用服务中的储存库和控制器中的服务

7kqas0il  于 2022-11-14  发布在  Spring
关注(0)|答案(2)|浏览(156)

我在编程时避免使用其他服务https://github.com/JonkiPro/REST-Web-Services/tree/master/core/src/main/java/com/core/jpa/service中的服务。我尝试在服务上只使用仓库。我目前正在编写一个使用两个服务的控制器。一个在云中保存文件,另一个从云中带有文件标识符的实体保存。

@PutMapping(value = "/contributions/{id}/photos")
@ResponseStatus(HttpStatus.NO_CONTENT)
public
void updatePhotoContribution(
        @PathVariable("id") final Long id,
        @RequestParam(required = false) Set<Long> elementIdsToAdd,
        @RequestPart(required = false) List<MultipartFile> elementsToAdd,
        @RequestPart(required = false) List<MultipartFile> newElementsToAdd,
        @RequestParam(required = false) Set<Long> idsToUpdate,
        @RequestPart(required = false) List<MultipartFile> elementsToUpdate,
        @RequestParam(required = false) Set<Long> idsToDelete,
        @RequestParam final Set<String> sources,
        @RequestParam(required = false) final String comment
) {
    Set<String> ids = new HashSet<>();

    for(files) {
        String id = this.storageService.save(...); // Save the file in the cloud with file identifiers stored in the cloud
        ids.add(id);
    }

    Contribution contribution = //create contribution

    try {
        this.movieContributionPersistenceService.updateReviewContribution(contribution, id, this.authorizationService.getUserId());
    } catch(ResourceNotFoundException e) {
        //  remove the file from the cloud
        throw new ResourceNotFoundException(e.getMessage());
    } catch(ResourceConflictException e) {
        //  remove the file from the cloud
        throw new ResourceConflictException(e.getMessage());
    }
}

这是我遇到的问题的唯一解决方案。如果我在movieContributionPersistenceService中使用storageService,它看起来会更好,但我坚持我只在服务上使用存储库的事实。您对此有何看法?
这是我之前基于相同原理创建的另一个控制器:https://pastebin.com/Ry1gcYdL

tyg4sfes

tyg4sfes1#

这不是一个灾难性的结构,以autowire服务内的另一个服务,但在这种方式,你会结束耦合您的服务,这可能会导致维护问题。
您可以创建一个具有公共功能的实用程序并使两个服务都使用它,而不是将您的服务耦合起来。

57hvy0tb

57hvy0tb2#

您希望在应用程序中遵循设计原则是:
1.您可以依赖服务类中的其他服务
1.你只能使用类的下一层,在你的例子中是仓库。
如果你选择了选项1,请记住,你可能会在你的spring Boot 应用程序中出现循环引用。
服务A -〉服务B -〉服务A
从 Spring Boot 2.6.0开始禁止循环参考,默认情况下禁止Spring循环参考。
所以最好有一个公共的服务类,避免循环引用,否则在使用其他服务引用时,保持服务的正确层次。

相关问题