微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Springfox Swagger无法向请求示例添加类

如何解决Springfox Swagger无法向请求示例添加类

我一直在尝试在Groovy REST应用程序中配置Springfox Swagger。

我的SwaggerConfig

@Configuration
@EnableSwagger2
public class SpringFoxConfig {

    @Bean
    public Docket apiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("edu.wsu.it.esg_apps.controller"))
                .paths(PathSelectors.ant("/api/**"))
                .build()
                .securityContexts(Arrays.asList(securityContext()))
                .securitySchemes(Arrays.asList(basicAuthScheme()));
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(Arrays.asList(basicAuthReference()))
                .forPaths(PathSelectors.ant("/api/**"))
                .build();
    }

    private SecurityScheme basicAuthScheme() {
        return new BasicAuth("basicAuth");
    }

    private SecurityReference basicAuthReference() {
        return new SecurityReference("basicAuth",new AuthorizationScope[0]);
    }
}

NoticeWithRecipientsRequest对象

class NoticeWithRecipientsRequest {

    NoticeFrame notice

    List<RecipientFrame> recipients

    NoticeWithRecipientsRequest(){}

    NoticeWithRecipientsRequest(NoticeFrame noticeFrame,List<RecipientFrame> recipientFrameList){
        this.notice = noticeFrame
        this.recipients = recipientFrameList
    }

    NoticeFrame getNotice(){
        return this.notice
    }

    void setNotice(NoticeFrame noticeFrame){
        this.notice = noticeFrame
    }

    List<RecipientFrame> getRecipients(){
        return this.recipients
    }

    void setRecipients(List<RecipientFrame> recipientFrameList){
        this.recipients = recipientFrameList
    }
}

NoticeFrame类

class NoticeFrame {

   @NotBlank(message = "Subject is missing")
    String subject

    @NotBlank(message = "Notice body is missing")
    String message

    String noticeGroup

    @NotBlank(message = "Creator id is missing")
    String creatorId

    @NotBlank(message = "Creator email is missing")
    String creatorEmail

    @NotBlank(message = "Creator name is missing")
    String creatorName

    @NotNull
    @Future(message = "Expiration date should be in the future")
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm a",timezone = "America/Los_Angeles")
    Date expiresAt
}

RecipientFrame类

class RecipientFrame {

    String wsuid

    String networkid
}

ApiController

@RestController
class ApiController {

    @Autowired
    RecipientRepository recipientRepository

    @Autowired
    private NoticeRepository noticeRepository //entity manager for notices

    @Autowired
    NoticeService noticeService

    @Autowired
    RecipientService recipientService
    
    Logger LOG = LoggerFactory.getLogger(ApiController.class)

    @PreAuthorize("hasAuthority('notices.creator')")
    @ApiOperation(value = "Create a Notice and assign it to a list of Recipients",response = NoticeWithRecipients.class,tags ="createNotice")
    @ApiImplicitParams(
            [
                    @ApiImplicitParam(
                            name = "notice",dataType = "NoticeWithRecipientsRequest"
//,example = "{\"notice\":{\"subject\": \"Test Demo 1\",\"message\": \"Testing stuff out.\",\"noticeGroup\": \"Business.Administration\",\"creatorId\": \"test.creator\",\"creatorEmail\": \"test.creator@wsu.edu\",\"creatorName\": \"Test Creator\",\"expiresAt\": \"2020-12-31 00:00 AM\"},\"recipients\":[{\"networkid\": \"john.doe\"},{\"networkid\": \"jane.doe\"}]}"
//,examples = @Example(value = [@ExampleProperty(value = "{\"notice\":{\"subject\": \"Test Demo 1\",{\"networkid\": \"jane.doe\"}]}",mediaType = "application/json")])
                    )
            ]
    )
    @PostMapping("api/create")
    ResponseEntity create(@Valid @RequestBody String notice,HttpServletRequest request)
    {
        ObjectMapper objectMapper = new ObjectMapper()
        NoticeWithRecipientsRequest noticeRequest = objectMapper.readValue(notice,NoticeWithRecipientsRequest.class)
        NoticeWithRecipients json = new NoticeWithRecipients(noticeRequest)
        List<Recipient> recipientList = new ArrayList<>()
        List<HashMap<String,Object>> invalid = new ArrayList<HashMap<String,Object>>()
        if(request.getParameter("valid") == "Y"){
            recipientList.addAll(json.getRecipients())
        }else{
            for (Recipient recipient : json.getRecipients()) {
                try{
                    Recipient thisRecipient = oktaService.GetRecipient(recipient.getWsuid().toString())
                    thisRecipient.setStatus("undelivered")
                    recipientList.add(thisRecipient)
                }catch(Exception ex){
                    try{
                        LOG.info("Failed to get a valid recipient object for ${recipient.getWsuid()} trying network id")
                        Recipient thisRecipient = oktaService.GetRecipient(recipient.getNetworkid().toString())
                        thisRecipient.setStatus("undelivered")
                        recipientList.add(thisRecipient)
                    }catch(Exception ex2){
                        LOG.info("Failed to get a valid recipient object for ${recipient.getNetworkid()} for the following reason: ${(ex2.getAt("undeclaredThrowable") as Exception).getMessage()}")
                        if(recipient.getEmail() == null){
                            recipient.setEmail("undeliverable@wsu.edu")
                        }
                        if(recipient.getName() == null){
                            recipient.setName("Invalid Data")
                        }
                        if(recipient.getNetworkid() == null){
                            recipient.setNetworkid("invalid.data")
                        }
                        if(recipient.getWsuid() == null){
                            recipient.setWsuid(Long.parseLong("111111111"))
                        }
                        recipient.setStatus("undeliverable")
                        recipientList.add(recipient)
                    }
                }

            }
        }
        if(recipientList.stream().filter{o -> o.getStatus() == "undelivered"}.collect().toList().size() != 0){
            Notice theNotice = noticeService.createNotice(json.notice)
            for (int i = 0; i < recipientList.size(); i++) {
                recipientList[i].setExpiresAt(theNotice.getExpiresAt())
                recipientList[i] = recipientService.createRecipient(theNotice.getId(),recipientList[i])
            }
            return ResponseEntity.status(200).body(new NoticeWithRecipients(theNotice,recipientList))

        }else{
            def badResponse = [:]
            badResponse."message" = "No valid recipients supplied"
            if(invalid.size()!= 0){
                badResponse."Failed" = invalid
            }
            return ResponseEntity.status(400).body(badResponse)
        }
    }
}

问题在于,在我的@ApiImplicParams声明中,NoticeWithRecipientsRequest没有进入应用程序。

Error Image

如果我添加一个将类声明为响应元素的端点,则一切正常。

但是,如果我将以下端点添加到控制器,那么一切都会按预期进行。

    @PreAuthorize("hasAuthority('notices.creator')")
    @ApiOperation(value = "Create a Notice and assign it to a list of Recipients",response = NoticeWithRecipientsRequest.class,tags ="check")
    @ApiImplicitParams(
            [
                    @ApiImplicitParam(
                            name = "notice",dataType = "NoticeWithRecipientsRequest"
                    )
            ]
    )
    @PostMapping("api/check")
    ResponseEntity validate(@Valid @RequestBody String notice)
    {
        ObjectMapper objectMapper = new ObjectMapper()
        NoticeWithRecipientsRequest noticeRequest = objectMapper.readValue(notice,NoticeWithRecipientsRequest.class)
       return ResponseEntity.status(200).body(noticeRequest)
    }

After additional endpoint

我尝试通过AdditionalModel和AlternativeTypeRules方法将类添加到Swagger配置中。如果我尝试检查方法,这两种方法都会导致应用程序花费10分钟以上的时间来启动,并且导致swagger-ui锁定。我尝试使用@ApiModel和@ApiModelProperty批注定义类,这会导致相同的行为。我知道这样做的原因是因为其他方法注释将类加载到Swagger文档中。但是,我在任何教程中都找不到一种方法,该方法可以让我将NoticeWithRecipientsRequest对象加​​载到实际有效的swagger定义中。我不确定是否有人可以在这里看到我做错的事情,或者是否有更好的方法生成草率的文档?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。