有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当我用SpringDoc和接口描述API规范时,java Spring控制器验证似乎不起作用

我的gradle多模块项目包含:

  1. “api spec”模块,包含rest控制器的java接口,用SpringDoc生成器描述api规范

  2. “wallet”模块,包含实现api规范接口的rest控制器的java类

我认为:

“api规范”模块->;钱包控制器。爪哇

@RequestMapping(path = "/wallet", produces = MediaType.APPLICATION_JSON_VALUE)
public interface WalletController {

    @Operation(summary = "Create wallet")
    @PostMapping(path = "/create-wallet")
    ApiResponseContainer<WalletDto> createWallet(@Valid @RequestBody ApiRequestContainer<CreateWalletRequestDto> request);
}

“钱包”模块->;WalletControllerImpl。爪哇:

@RestController
@Slf4j
public class WalletControllerImpl implements WalletController {
    @Override
    public ApiResponseContainer<WalletDto> createWallet(ApiRequestContainer<CreateWalletRequestDto> request) {
        /* validation does not perform in this case */
    }
}

当我在一个类中创建控制器参数时,我希望Spring以完全相同的方式验证它:

好管制员。爪哇:

@RequestMapping(path = "/good")
public class GoodController {
    @PostMapping
    public ApiResponseContainer<SomeDto> someMethod(@Valid @RequestBody SomeBodyDto bodyDto) {
        /* request is well validated here */
    }
}
}

有人面临这个问题吗


共 (1) 个答案

  1. # 1 楼答案

    嗯。。。这似乎是我的通用请求主体的问题

    检查差异:

    验证“不起作用”:

    public class ApiRequestContainer<T> {
    
        @Schema(description = "Request content")
        @NotNull
        T request;
    
        @Schema(description = "Signature of request content")
        @NotNull
        String signature;
    
    }
    

    验证id工作:

    public class ApiRequestContainer<T> {
    
        @Schema(description = "Request content")
        @Valid
        @NotNull
        T request;
    
        @Schema(description = "Signature of request content")
        @NotNull
        String signature;
    
    }
    
    

    当我标记@Valid容器的通用字段时,它开始工作