Springbootプロジェクト統合Swagger 2ピットへの旅


現段階では,JavaWeb開発,前後の分離が主流となっている.開発段階では、前後のエンジニアがデータインタラクティブインターフェースを約束し、並列開発とテストを実現する.実行フェーズ前後のエンド分離モードでは、Webアプリケーションを分離配置する必要があり、フロントエンドではhttpまたは他のプロトコルを使用してインタラクティブに要求されます.したがって,バックグラウンドインタフェースサービスでは,swaggerを用いてインタフェースとその情報を定義することができる.swaggerの详しい情报について、みんなはホームページに行ってSwaggerの公式サイトをブラウズすることができます:私の感じはそれが1种の可視化のデバッグツールで、ハハハ....次にspringbootプロジェクトでSwaggerを統合する方法を見てみましょう.1、pom.xmlの構成
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2、swagger構成クラスの作成
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2).
                apiInfo(apiInfo()).
                select().
                apis(RequestHandlerSelectors.basePackage("com.example.examonlineweb.controller")).
                paths(PathSelectors.any()).
                build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder().
                title("          swagger2  restful api").
                description("    springboot     swagger2").
                contact("xxxxxx").
                version("1.0").build();
    }
}

3、この起動クラスに注釈を付ける
@EnableSwagger2

4、注意:springbootプロジェクト統合swaggerは両者のバージョンに注意しなければならない.springbootプロジェクトのバージョンは低く、対応するswaggerバージョンはあまり高くない.逆に、プロジェクトのエラーを避ける.例えば、springbootバージョンは2.2.1、swaggerバージョンは2.2.2で、プロジェクトの起動は次のエラーを報告します.
2019-12-08 16:17:00.058  INFO 8976 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-12-08 16:17:00.534  WARN 8976 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'linkDiscoverers' defined in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]: Unsatisfied dependency expressed through method 'linkDiscoverers' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.plugin.core.PluginRegistry' available: expected single matching bean but found 15: modelBuilderPluginRegistry,modelPropertyBuilderPluginRegistry,typeNameProviderPluginRegistry,documentationPluginRegistry,apiListingBuilderPluginRegistry,operationBuilderPluginRegistry,parameterBuilderPluginRegistry,expandedParameterBuilderPluginRegistry,resourceGroupingStrategyRegistry,operationModelsProviderPluginRegistry,defaultsProviderPluginRegistry,pathDecoratorRegistry,relProviderPluginRegistry,linkDiscovererRegistry,entityLinksPluginRegistry
2019-12-08 16:17:00.535  INFO 8976 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2019-12-08 16:17:00.539  INFO 8976 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-12-08 16:17:00.549  INFO 8976 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
Disconnected from the target VM, address: '127.0.0.1:64025', transport: 'socket'
2019-12-08 16:17:00.554 ERROR 8976 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method linkDiscoverers in org.springframework.hateoas.config.HateoasConfiguration required a single bean, but 15 were found:
	- modelBuilderPluginRegistry: defined in null
	- modelPropertyBuilderPluginRegistry: defined in null
	- typeNameProviderPluginRegistry: defined in null
	- documentationPluginRegistry: defined in null
	- apiListingBuilderPluginRegistry: defined in null
	- operationBuilderPluginRegistry: defined in null
	- parameterBuilderPluginRegistry: defined in null
	- expandedParameterBuilderPluginRegistry: defined in null
	- resourceGroupingStrategyRegistry: defined in null
	- operationModelsProviderPluginRegistry: defined in null
	- defaultsProviderPluginRegistry: defined in null
	- pathDecoratorRegistry: defined in null
	- relProviderPluginRegistry: defined by method 'relProviderPluginRegistry' in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]
	- linkDiscovererRegistry: defined in null
	- entityLinksPluginRegistry: defined by method 'entityLinksPluginRegistry' in class path resource [org/springframework/hateoas/config/WebMvcEntityLinksConfiguration.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed


Process finished with exit code 1


そこで、私はswaggerのバージョンを2.9.2に昇格させて、プロジェクトはOKを起動します.ここでは、穴に入らないように注意してください.これで、swaggerの統合が完了し、次にインタフェースを書くことができます.5、実例
package com.example.springbootweb.controller;

import com.example.springbootweb.entity.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/users")
public class UserController {
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long,User>());

    @ApiOperation(value="      ",notes = "")
    @RequestMapping(value={""},method = RequestMethod.GET)
    public List<User> getUsers(){
        List<User> u = new ArrayList<>(users.values());
        return u;
    }

    @ApiOperation(value="    ",notes = "  User      ")
    @ApiImplicitParam(name="user",value="      user",required = true,dataType = "User")
    @RequestMapping(value="", method=RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value="        ",notes = "  id  ")
    @ApiImplicitParam(name="id",value="  id",required = true,dataType = "Long",paramType = "path")
    @RequestMapping(value="/{id}",method = RequestMethod.GET)
    /*@ApiImplicitParam(name="id",value="  id",required = true,dataType = "Long",paramType = "query")
    @RequestMapping(value="/edit",method = RequestMethod.GET)*/
    public User getById(@PathVariable Long id){
        return users.get(id);
    }

    @ApiOperation(value="      ",notes = "  id  ")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="  id",required = true,dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name="user",value="      User",required = true,dataType = "User")
    })
    @RequestMapping(value="/{id}",method = RequestMethod.PUT)
    public String update(@PathVariable Long id,@RequestBody User user){
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id,u);
        return "success";
    }

    @ApiOperation(value="    ",notes = "  id    ")
    @ApiImplicitParam(name="id",value="  id",required = true,dataType = "Long",paramType = "path")
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable Long id){
        users.remove(id);
        return "success";
    }
}


http://localhost:8080/swagger-ui.htmlからアクセスできます.