Spring Boot App无法注册RequestContextListener

时间:2018-10-20 11:11:07

标签: java spring spring-boot spring-web

我正在创建简单的REST控制器,为此我在Spring Boot应用程序中添加了RequestContextListener

的配置。
@Configuration
@WebListener
public class DataApiRequestContextListener extends RequestContextListener {

}

在控制器中,我尝试ot构建位置标头以成功发布请求

@Async("webExecutor")
@PostMapping("/company")
public CompletableFuture<ResponseEntity<Object>> save(@RequestBody Company company) {

    Company savedCompany = companyRepository.save(company);

    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(savedCompany.getId()).toUri();

    ResponseEntity<Object> response = ResponseEntity.created(location).build();
    LOGGER.debug("Reponse Status for POST Request is :: " + response.getStatusCodeValue());
    LOGGER.debug("Reponse Data for POST Request is :: " + response.getHeaders().getLocation().toString());
    return CompletableFuture.completedFuture(response);
}

我得到了例外

java.lang.IllegalStateException: No current ServletRequestAttributes

当我尝试在此行使用ServletUriComponentsBuilder构建位置URI

URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                    .buildAndExpand(savedCompany.getId()).toUri();

1 个答案:

答案 0 :(得分:2)

如果使用fromRequestUri则使用@async

@Async("webExecutor")
@PostMapping("/company")
public CompletableFuture<ResponseEntity<Object>> save(HttpServletRequest request, @RequestBody Company company) {

    Company savedCompany = companyRepository.save(company);

    URI location = ServletUriComponentsBuilder.fromRequestUri(request).path("/{id}")
                .buildAndExpand(savedOrganization.getId()).toUri();

    ResponseEntity<Object> response = ResponseEntity.created(location).build();
    LOGGER.debug("Reponse Status for POST Request is :: " + response.getStatusCodeValue());
    LOGGER.debug("Reponse Data for POST Request is :: " + response.getHeaders().getLocation().toString());
    return CompletableFuture.completedFuture(response);
}

不带@async的OR应该可以正常工作,并返回您的位置uri。

@PostMapping("/company")
public CompletableFuture<ResponseEntity<Object>> save(@RequestBody Company company) {

    Company savedCompany = companyRepository.save(company);

    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(savedCompany.getId()).toUri();

    ResponseEntity<Object> response = ResponseEntity.created(location).build();
    LOGGER.debug("Reponse Status for POST Request is :: " + response.getStatusCodeValue());
    LOGGER.debug("Reponse Data for POST Request is :: " + response.getHeaders().getLocation().toString());
    return CompletableFuture.completedFuture(response);
}