在哪里放置 swagger 生成的服务器代码的代码

where to put code for swagger generated server code

我刚开始大摇大摆地生成一个javaSpringAPI。 这一代人本身没有问题。我使用 PetStore yaml 毫无问题地生成了 Spring 引导服务器端代码。

生成代码后,我找不到合适的 tutorial/way 向我解释将我要编写的自定义代码放在哪里最好。将它直接写入生成的代码似乎不是一个好主意,因为如果我因为定义的更改而重新生成你不想覆盖使用的代码。

你会得到像这样的存根:

@Controller
public class PetApiController implements PetApi {
...
  public ResponseEntity<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,
    @ApiParam(value = "Additional data to pass to server") @RequestPart(value="additionalMetadata", required=false)  String additionalMetadata,
      @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) {
      // do some magic!
      return new ResponseEntity<ModelApiResponse>(HttpStatus.OK);
  }
...
}

现在有没有办法通过调用服务来填充 "do some magic!" 部分 during/after 生成,这样我就可以将其用作某种入口点。例如自动装配一个具有相同方法但可以由我提供的服务,这样我就可以将我的实现与生成的代码分开。

@Controller
public class PetApiController implements PetApi {
...
@Autowired
PetApiService petApiService;
...
  public ResponseEntity<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,
    @ApiParam(value = "Additional data to pass to server") @RequestPart(value="additionalMetadata", required=false)  String additionalMetadata,
      @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) {
      return petApiService.uploadFile(file);
  }
...
}

谢谢

没有简单的方法可以使用 Swagger 重新生成新代码并阻止它覆盖您想要编写的任何代码。如果你想更改 api,有一种方法可以减轻所有的复制粘贴。与其在 "do some magic" 注释上编写所有代码,不如尝试在外部 class 中写入一个方法,因此如果您需要使用 swagger 重新生成代码,您只需要复制一个单行,我举个例子:

@Controller
public class PetApiController implements PetApi {

@Autowired
GenerateResponse generateResponse;
...
  public ResponseEntity<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,
    @ApiParam(value = "Additional data to pass to server") @RequestPart(value="additionalMetadata", required=false)  String additionalMetadata,
      @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) {
      return generateResponse.uploadFile(petId, additionalMetadata, file);
  }
...
}

在你外面 class 我叫 "GenerateResponse":

@Component
public class GenerateResponse{
@Autowired
PetApiService petApiService;

    public ResponseEntity<ModelApiResponse> uploadFile(Long petId, String additionalMetadata, MultipartFile file){
    return petApiService.uploadFile(file);
    }
}

所以你只需要复制 "return GenerateResponse.uploadFile(petId, additionalMetadata, file);" 行,每次更改它时只创建一次自动装配的 GenerateResponse。