春季启动:避免复制粘贴URIComponentBuilder

时间:2018-10-19 08:53:38

标签: spring spring-boot

当前,我们正在针对要向端点发出的每个请求复制并粘贴此代码段。

URI applicationURI = UriComponentsBuilder
    .fromHttpUrl(
        this.backOfficeProperties.getFrontOfficeUrl() + "/" + reference.getId()
    )
    .queryParam(
        SecurityConstants.REQUEST_PARAMETER_APP,
        this.backOfficeProperties.getName()
    ).build().toUri();

如您所见,此代码经过修改后可以向uri中添加application个查询参数:endpoint?application=sdfsdf

因此,由于我们要为每个新请求处理此代码,因此out代码变得有些棘手:

public ReferenceComposition getReference(final URI uri) {

    URI applicationURI = UriComponentsBuilder
        .fromHttpUrl(backOfficeProperties.getFrontOfficeUrl())
        .queryParam(
            SecurityConstants.REQUEST_PARAMETER_APP,
            this.backOfficeProperties.getName()
        ).build().toUri();

    ResponseEntity<Resource> response = this.restTemplate
        .getForEntity(
            applicationURI,    
            Resource.class
        );

    return this.extractReferenceFromResponse(response);
}

public void referenceProcessed(ReferenceBase reference) {

    URI applicationURI = UriComponentsBuilder
        .fromHttpUrl(
            this.backOfficeProperties.getFrontOfficeUrl() + "/" + reference.getId()
        )
        .queryParam(
            SecurityConstants.REQUEST_PARAMETER_APP,
            this.backOfficeProperties.getName()
        ).build().toUri();

    this.restTemplate
        .put(
            applicationURI,
            reference
        );
}

有什么方法可以使用更优雅的方式解决它?

0 个答案:

没有答案