如何在Spring Boot OpenAPI委托类中获取HTTP请求引用?
问题:在OpenAPI代码生成器的Spring Boot委托类中获取HTTP请求引用
我正尝试使用Spring Boot和OpenAPI代码生成器实现OpenAPI规范,已生成基于示例规范的OpenAPI桩代码。当前编写的实现类如下:
public class PetApiDelegateImpl implements PetApiDelegate { /** * POST /pet : Add a new pet to the store * Add a new pet to the store * * @param pet Create a new pet in the store (required) * @return Successful operation (status code 200) * or Invalid input (status code 400) * or Validation exception (status code 422) * @see PetApi#addPet */ @Override ResponseEntity<Pet> addPet(Pet pet) { // TODO: fill out the implementation } }
遇到的问题是,希望在该方法中获取HTTP请求的引用,但生成的桩代码中PetApiDelegate接口的getRequest()方法仅返回空请求:
/** * A delegate to be called by the {@link PetApiController}}. * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. */ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2024-04-10T14:44:58.115530-07:00[America/Los_Angeles]", comments = "Generator version: 7.4.0") public interface PetApiDelegate { default Optional<NativeWebRequest> getRequest() { return Optional.empty(); } }
解决方案
方法1:修改代码生成配置,让Delegate自动注入请求
在生成代码时,通过配置让OpenAPI代码生成器生成支持请求注入的PetApiDelegate接口:
- 若使用Maven插件,在插件配置中添加以下参数:
<configuration> <configOptions> <delegatePattern>true</delegatePattern> <useSpringNativeWebRequest>true</useSpringNativeWebRequest> </configOptions> </configuration>
重新生成代码后,getRequest()方法会返回当前的NativeWebRequest实例,你可以在实现类中直接使用:
@Override ResponseEntity<Pet> addPet(Pet pet) { NativeWebRequest nativeRequest = getRequest() .orElseThrow(() -> new IllegalStateException("当前无可用请求")); HttpServletRequest httpRequest = nativeRequest.getNativeRequest(HttpServletRequest.class); // 在这里使用httpRequest获取请求头、参数等信息 return ResponseEntity.ok(pet); }
方法2:使用Spring RequestContextHolder手动获取请求
如果不想重新生成代码,可直接利用Spring的RequestContextHolder工具类获取当前请求:
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @Override ResponseEntity<Pet> addPet(Pet pet) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null) { HttpServletRequest httpRequest = attributes.getRequest(); // 处理请求相关逻辑 } return ResponseEntity.ok(pet); }
内容的提问来源于stack exchange,提问作者morpheus
相关产品推荐
相关产品推荐

