精华内容
下载资源
问答
  • 微服务之Swagger

    2020-11-03 11:20:43
  • 微服务之swagger

    2018-06-05 14:33:56
    Swagger使用 添加依赖 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <...

    Swagger使用

    添加依赖

    <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>

    配置类

    @Configuration  
    @EnableSwagger2  
    public class Swagger2 {
    
        public static final String SWAGGER_SCAN_BASE_PACKAGE = "abc.boot.examples.web";
        public static final String VERSION = "1.0.0";
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))//api接口包扫描路径
                    .paths(PathSelectors.any())//可以根据url路径设置哪些请求加入文档,忽略哪些请求
                    .build();
        }
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                .title("Swagger2 接口文档示例")//设置文档的标题
                .description("更多内容请关注:http://www.abc.com")//设置文档的描述->1.Overview
                .version(VERSION)//设置文档的版本信息-> 1.1 Version information
                .contact(new Contact("ABC Boot", "http://www.abc.comt", ""))//设置文档的联系方式->1.2 Contact information
                .termsOfServiceUrl("www.abc.com")//设置文档的License信息->1.3 License information
                .build();
        }
    }

    注解使用
    @ApiOperation

    @ApiOperation(value="获取用户列表", notes="获取所有用户列表",produces = "application/json")  
    @RequestMapping(value="/users", method= RequestMethod.GET)
    public List<User> getUserList() {  
    List<User> r = new ArrayList<User>(users.values());
        return r;
    }

    @ApiResponses

    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息",produces = "application/json")
    // ApiResponses 增加返回结果的描述
    @ApiResponses(value = {@ApiResponse(code = 405,message = "Invalid input",response = Integer.class)}) (1)
    @ApiImplicitParam(name = "id",value = "用户ID",dataType = "int",paramType = "path")  (2)
    @RequestMapping(value="/users/{id}", method= RequestMethod.GET)
    public User getUser(@PathVariable Integer id) {
        return users.get(id);
    }

    (1) 在默认Response的基础上增加新的Response说明
    (2) 使用ApiImplicitParam描述接口参数

    @ApiImplicitParams

    @ApiOperation(value="更新用户名称", notes="更新指定用户的名称")
    @RequestMapping(value="/users/{id}", method= RequestMethod.POST)
    @ApiImplicitParams({  (1)
            @ApiImplicitParam(name = "id",value = "用户ID",paramType = "path",dataType = "int"),  (2)
            @ApiImplicitParam(name = "userName",value = "用户名称",paramType = "form",dataType = "string")
    })
    public void updateUserName(@PathVariable Integer id,@RequestParam String userName){
        User u = users.get(id);
        u.setName(userName);
    }

    (1) 使用ApiImplicitParams描述多个参数
    (2) 使用ApiImplicitParam时,需要指定paramType,这样也便于swagger ui 生成参数的输入格式。

    paramType 有五个可选值 : path, query, body, header, form

    @ApiParam

    @ApiOperation(value="创建用户-传递简单对象", notes="传递简单对象",produces = "application/json")
    @RequestMapping(value="/users-1", method= RequestMethod.POST)
    //可以不加ApiParam注解,需要给参数添加描述时可以使用这个注解,或者使用ApiImplicitParams注解 (1)
    public Map postUser(@RequestParam  String userName,@ApiParam("地址") @RequestParam(required = false) String address) { 
        User user = new User();
        user.setId(Math.round(10));
        user.setName(userName);
        user.setAddress(address);
        users.put(user.getId(), user);
        return ImmutableMap.of("user",user);
    }

    (1) 使用ApiParam描述接口参数

    ApiImplicitParam 与 ApiParam 的区别
    ApiImplicitParam: This is the only way to define parameters when using Servlets or other non-JAX-RS environments.

    • 对Servlets或者非 JAX-RS的环境,只能使用 ApiImplicitParam。
    • 在使用上,ApiImplicitParam比ApiParam具有更少的代码侵入性,只要写在方法上就可以了,但是需要提供具体的属性才能配合swagger ui解析使用。
    • ApiParam只需要较少的属性,与swagger ui配合更好。

    传递复杂对象 By ModelAttribute

    @ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO, url参数拼接",produces = "application/json")
    @RequestMapping(value="/users-2", method= RequestMethod.POST)
    //传递对象推荐使用ModelAttribute注解
    public Map postUser2(@ModelAttribute User user) {  
        users.put(user.getId(),user);
        return ImmutableMap.of("user",user);
    }

    (1) ModelAttribute 是Spring mvc的注解,这里Swagger可以解析这个注解,获得User的属性描述

    @ApiModel

    @ApiModel(value = "User", description = "用户对象")
    public class User {
    
        @ApiModelProperty(value = "ID")
        private Integer id;
        @ApiModelProperty(value = "姓名")
        private String name;
        @ApiModelProperty(value = "地址")
        private String address;
        @ApiModelProperty(value = "年龄",access = "hidden")
        private int age;
        @ApiModelProperty(value = "性别")
        private int sex;
        .......
    }

    传递复杂对象 By RequestBody

    @ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO,json格式传递数据",produces = "application/json")
    @RequestMapping(value="/users-3", method= RequestMethod.POST)
    //json格式传递对象使用RequestBody注解
    public User postUser3(@RequestBody User user) {
        users.put(user.getId(),user);
        return user;
    }

    PathVariable

    @ApiOperation(value="删除用户- PathVariable", notes="根据url的id来指定删除对象")
    @RequestMapping(value="/users/{id}", method = RequestMethod.DELETE)
    public void deleteUser(@PathVariable Integer id) {  (1)
        users.remove(id);
    }

    (1) PathVariable是Spring 的注解,对于这种简单的参数,就可以不用写ApiParam来描述接口参数。

    数组的描述

    @ApiOperation(value="删除用户-传递数组", notes="删除对象,传递数组")
    @RequestMapping(value="/users/deleteByIds", method = RequestMethod.DELETE)
    public void deleteUser(@ApiParam("用户ID数组") @RequestParam Integer[] ids) {  (1)
        for (int id:ids){
            users.remove(id);
        }
    }

    (1) 这里用ApiParam为数组参数添加描述

    可选配置

    在application.properties中加入以下配置,用于设置测试请求的host,默认在swagger ui上做请求测试时都是以/users/1为路径发送请求。
    如果需要改变请求的根路径,就需要配置这个参数:
    springfox.documentation.swagger.v2.host = yourapp.abc.com

    配置获取api docs json数据的请求路径 ,默认为/v2/api-docs:
    springfox.documentation.swagger.v2.path = /api

    springfox-staticdocs生成静态文档

    这里写图片描述
    Springfox

    Maven配置

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-staticdocs</artifactId>
        <version>2.2.2</version>
        <scope>test</scope>
    </dependency>

    生成json文件

    编写Junit测试,这样在测试环节就可以将api-docs的json数据写入文档,便于下一步生成asciidoc文件。
    
    @WebAppConfiguration
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = DemoBootApplication.class)
    public class Swagger2MarkupTest {
    
        @Autowired
        private WebApplicationContext context;
    
        private MockMvc mockMvc;
    
        @Before
        public void setUp() {
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
        }
    
        @Test
        public void createSpringfoxSwaggerJson() throws Exception {
            String outputDir = "src/docs/json";  //将api-docs的json数据写入文件
            MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
                    .accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk())
                    .andReturn();
    
            MockHttpServletResponse response = mvcResult.getResponse();
            String swaggerJson = response.getContentAsString();
            Files.createDirectories(Paths.get(outputDir));
            try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)) {
                writer.write(swaggerJson);
            }
        }
    }

    配置maven插件

    配置以下两个插件:
    swagger2markup-maven-plugin,该插件将json文件转为asciidoc
    asciidoctor-maven-plugin, 该插件将asciidoc转为html/pdf

    执行Maven命令 : mvn swagger2markup:convertSwagger2markup process-resources

    生成的html文档存储在src\main\resources\META-INF\resources\docs目录下。
    启动DemoBootApplication,直接访问http://localhost:8080/docs/index.html

    <pluginRepositories>
        <pluginRepository>
            <id>jcenter-snapshots</id>
            <name>jcenter</name>
            <url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
        </pluginRepository>
        <pluginRepository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>jcenter-releases</id>
            <name>jcenter</name>
            <url>http://jcenter.bintray.com</url>
        </pluginRepository>
    </pluginRepositories>
    
    <build>
        <plugins>
            <!-- First, use the swagger2markup plugin to generate asciidoc -->
            <plugin>
                <groupId>io.github.swagger2markup</groupId>
                <artifactId>swagger2markup-maven-plugin</artifactId>
                <version>${swagger2markup.plugin.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>io.github.swagger2markup</groupId>
                        <artifactId>swagger2markup-import-files-ext</artifactId>
                        <version>${swagger2markup.extension.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>io.github.swagger2markup</groupId>
                        <artifactId>swagger2markup</artifactId>
                        <version>${swagger2markup.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <!--The URL or file path to the Swagger specification-->
                    <swaggerInput>${swagger.input}</swaggerInput>
                    <outputDir>${generated.asciidoc.directory}</outputDir>
                    <config>
                        <!--设置输出文件的语言:ASCIIDOC, MARKDOWN, CONFLUENCE_MARKUP-->
                        <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
                        <!--设置目录的展现方式-->
                        <swagger2markup.pathsGroupedBy>TAGS</swagger2markup.pathsGroupedBy>
                        <!--扩展Overview的内容,可以增加一些自定义的内容-->
                        <!--<swagger2markup.extensions.dynamicOverview.contentPath>${project.basedir}/src/docs/asciidoc/extensions/overview</swagger2markup.extensions.dynamicOverview.contentPath>
                        <swagger2markup.extensions.dynamicDefinitions.contentPath>${project.basedir}/src/docs/asciidoc/extensions/definitions</swagger2markup.extensions.dynamicDefinitions.contentPath>
                        <swagger2markup.extensions.dynamicPaths.contentPath>${project.basedir}/src/docs/asciidoc/extensions/paths</swagger2markup.extensions.dynamicPaths.contentPath>
                        <swagger2markup.extensions.dynamicSecurity.contentPath>${project.basedir}src/docs/asciidoc/extensions/security</swagger2markup.extensions.dynamicSecurity.contentPath>-->
                    </config>
                </configuration>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>convertSwagger2markup</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    
    
    
            <!-- Run the generated asciidoc through Asciidoctor to generate
                 other documentation types, such as PDFs or HTML5 -->
            <plugin>
                <groupId>org.asciidoctor</groupId>
                <artifactId>asciidoctor-maven-plugin</artifactId>
                <version>1.5.3</version>
                <!-- Include Asciidoctor PDF for pdf generation -->
                <dependencies>
                    <dependency>
                        <groupId>org.asciidoctor</groupId>
                        <artifactId>asciidoctorj-pdf</artifactId>
                        <version>1.5.0-alpha.11</version>
                    </dependency>
                    <!-- Comment this section to use the default jruby artifact provided by the plugin -->
                    <dependency>
                        <groupId>org.jruby</groupId>
                        <artifactId>jruby-complete</artifactId>
                        <version>${jruby.version}</version>
                    </dependency>
                    <!-- Comment this section to use the default AsciidoctorJ artifact provided by the plugin -->
                    <dependency>
                        <groupId>org.asciidoctor</groupId>
                        <artifactId>asciidoctorj</artifactId>
                        <version>${asciidoctorj.version}</version>
                    </dependency>
                </dependencies>
                <!-- Configure generic document generation settings -->
                <configuration>
                    <!--默认指向 ${basedir}/src/main/asciidoc-->
                    <sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>
                    <!--an override to process a single source file; 默认指向 ${sourceDirectory} 中的所有文件-->
                    <!--<sourceDocumentName>index.adoc</sourceDocumentName>-->
                    <attributes>
                        <doctype>book</doctype>
                        <toc>left</toc>
                        <toclevels>3</toclevels>
                        <numbered></numbered>
                        <hardbreaks></hardbreaks>
                        <sectlinks></sectlinks>
                        <sectanchors></sectanchors>
                        <generated>${generated.asciidoc.directory}</generated>
                    </attributes>
                </configuration>
                <!-- Since each execution can only handle one backend, run
                     separate executions for each desired output type -->
                <executions>
                    <execution>
                        <id>output-html</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>process-asciidoc</goal>
                        </goals>
                        <configuration>
                            <backend>html5</backend>
                            <outputDirectory>${asciidoctor.html.output.directory}</outputDirectory>
                        </configuration>
                    </execution>
    
    
                    <!-- 生成PDF -->
                    <!--<execution>
                        <id>output-pdf</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>process-asciidoc</goal>
                        </goals>
                        <configuration>
                            <backend>pdf</backend>
                            <outputDirectory>${asciidoctor.pdf.output.directory}</outputDirectory>
                        </configuration>
                    </execution>-->
    
                </executions>
            </plugin>
        </plugins>
    </build>

    其他说明

    如何修改/v2/api-docs路径?

    swagger-ui是通过获取接口的json数据渲染页面的,即通过swagger的注解将生成接口的描述服务,默认地址为/v2/api-docs,如果需要改变这个请求地址,可以在properties中配置springfox.documentation.swagger.v2.path。

    如何设置所有请求的统一前缀?

    默认请求都是以 / 根路径开始,如果我们的应用不是部署在根路径,比如以/platform部署,则可以通过一下方式设置请求的统一前缀。

    @Bean
    public Docket createV1RestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                .paths(PathSelectors.any()) 
                .build()
                .pathMapping("/platform"); // 在这里可以设置请求的统一前缀
    }

    设置响应对象的Example

    通过ApiModelProperty注解的example属性设置响应对象的示例:

    @ApiModelProperty(value = "ID",example = "1")
    private Integer id;
    @ApiModelProperty(value = "姓名",example = "Admin")
    private String name;
    @ApiModelProperty(value = "地址",example = "171")
    private String address;
    @ApiModelProperty(value = "年龄",access = "hidden",example = "20")
    private int age;
    @ApiModelProperty(value = "性别",example = "1")
    private int sex;
    @ApiModelProperty(value = "生日",example = "2000-10-22")
    展开全文
  • io.springfoxspringfox-boot-starter3.0.0新的访问路径:http://localhost:yourPort/v3/api-docshttp://localhost:yourPort/swagger-ui/index.htmlimportorg.springframework.boot.SpringApplication;i...

    spring boot 2.X推荐使用:

    io.springfox

    springfox-boot-starter

    3.0.0

    新的访问路径:

    http://localhost:yourPort/v3/api-docs

    http://localhost:yourPort/swagger-ui/index.html

    importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importspringfox.documentation.oas.annotations.EnableOpenApi;/*** Created by tang.cheng on 2017/4/22.*/@EnableOpenApi

    @SpringBootApplicationpublic classLearningDemoApplication {public static voidmain(String[] args) {

    SpringApplication.run(LearningDemoApplication.class, args);

    }

    }

    增加注解:@EnableOpenApi

    https://github.com/helloworldtang/spring-boot-cookbook/blob/master/learning-demo

    spring boot1.X下建议使用:

    https://github.com/SpringForAll/spring-boot-starter-swagger

    com.spring4all

    swagger-spring-boot-starter

    1.7.1.RELEASE

    Swagger使用

    1. Swagger UI

    1.1 添加依赖

    io.springfox

    springfox-swagger2

    2.2.2

    io.springfox

    springfox-swagger-ui

    2.2.2

    1.2 配置类

    @Configuration

    @EnableSwagger2

    public class Swagger2 {

    public static final String SWAGGER_SCAN_BASE_PACKAGE = "abc.boot.examples.web";

    public static final String VERSION = "1.0.0";

    @Bean

    public Docket createRestApi() {

    return new Docket(DocumentationType.SWAGGER_2)

    .apiInfo(apiInfo())

    .select()

    .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))//api接口包扫描路径

    .paths(PathSelectors.any())//可以根据url路径设置哪些请求加入文档,忽略哪些请求

    .build();

    }

    private ApiInfo apiInfo() {

    return new ApiInfoBuilder()

    .title("Swagger2 接口文档示例")//设置文档的标题

    .description("更多内容请关注:http://www.abc.com")//设置文档的描述->1.Overview

    .version(VERSION)//设置文档的版本信息-> 1.1 Version information

    .contact(new Contact("ABC Boot", "http://www.abc.comt", ""))//设置文档的联系方式->1.2 Contact information

    .termsOfServiceUrl("www.abc.com")//设置文档的License信息->1.3 License information

    .build();

    }

    }

    1.3 注解使用

    @ApiOperation

    @ApiOperation(value="获取用户列表", notes="获取所有用户列表",produces = "application/json")

    @RequestMapping(value="/users", method= RequestMethod.GET)

    public List getUserList() {

    List r = new ArrayList(users.values());

    return r;

    }

    @ApiResponses

    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息",produces = "application/json")

    // ApiResponses 增加返回结果的描述

    @ApiResponses(value = {@ApiResponse(code = 405,message = "Invalid input",response = Integer.class)}) (1)

    @ApiImplicitParam(name = "id",value = "用户ID",dataType = "int",paramType = "path") (2)

    @RequestMapping(value="/users/{id}", method= RequestMethod.GET)

    public User getUser(@PathVariable Integer id) {

    return users.get(id);

    }

    (1) 在默认Response的基础上增加新的Response说明

    (2) 使用ApiImplicitParam描述接口参数

    @ApiImplicitParams

    @ApiOperation(value="更新用户名称", notes="更新指定用户的名称")

    @RequestMapping(value="/users/{id}", method= RequestMethod.POST)

    @ApiImplicitParams({ (1)

    @ApiImplicitParam(name = "id",value = "用户ID",paramType = "path",dataType = "int"), (2)

    @ApiImplicitParam(name = "userName",value = "用户名称",paramType = "form",dataType = "string")

    })

    public void updateUserName(@PathVariable Integer id,@RequestParam String userName){

    User u = users.get(id);

    u.setName(userName);

    }

    (1) 使用ApiImplicitParams描述多个参数

    (2) 使用ApiImplicitParam时,需要指定paramType,这样也便于swagger ui 生成参数的输入格式。

    paramType 有五个可选值 : path, query, body, header, form

    @ApiParam

    @ApiOperation(value="创建用户-传递简单对象", notes="传递简单对象",produces = "application/json")

    @RequestMapping(value="/users-1", method= RequestMethod.POST)

    //可以不加ApiParam注解,需要给参数添加描述时可以使用这个注解,或者使用ApiImplicitParams注解 (1)

    public Map postUser(@RequestParam String userName,@ApiParam("地址") @RequestParam(required = false) String address) {

    User user = new User();

    user.setId(Math.round(10));

    user.setName(userName);

    user.setAddress(address);

    users.put(user.getId(), user);

    return ImmutableMap.of("user",user);

    }

    (1) 使用ApiParam描述接口参数

    ApiImplicitParam 与 ApiParam 的区别

    ApiImplicitParam: This is the only way to define parameters when using Servlets or other non-JAX-RS environments.

    对Servlets或者非 JAX-RS的环境,只能使用 ApiImplicitParam。

    在使用上,ApiImplicitParam比ApiParam具有更少的代码侵入性,只要写在方法上就可以了,但是需要提供具体的属性才能配合swagger ui解析使用。

    ApiParam只需要较少的属性,与swagger ui配合更好。

    传递复杂对象 By ModelAttribute

    @ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO, url参数拼接",produces = "application/json")

    @RequestMapping(value="/users-2", method= RequestMethod.POST)

    //传递对象推荐使用ModelAttribute注解

    public Map postUser2(@ModelAttribute User user) { (1)

    users.put(user.getId(),user);

    return ImmutableMap.of("user",user);

    }

    (1) ModelAttribute 是Spring mvc的注解,这里Swagger可以解析这个注解,获得User的属性描述

    @ApiModel

    @ApiModel(value = "User", description = "用户对象")

    public class User {

    @ApiModelProperty(value = "ID")

    private Integer id;

    @ApiModelProperty(value = "姓名")

    private String name;

    @ApiModelProperty(value = "地址")

    private String address;

    @ApiModelProperty(value = "年龄",access = "hidden")

    private int age;

    @ApiModelProperty(value = "性别")

    private int sex;

    .......

    }

    传递复杂对象 By RequestBody

    @ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO,json格式传递数据",produces = "application/json")

    @RequestMapping(value="/users-3", method= RequestMethod.POST)

    //json格式传递对象使用RequestBody注解

    public User postUser3(@RequestBody User user) {

    users.put(user.getId(),user);

    return user;

    }

    PathVariable

    @ApiOperation(value="删除用户- PathVariable", notes="根据url的id来指定删除对象")

    @RequestMapping(value="/users/{id}", method = RequestMethod.DELETE)

    public void deleteUser(@PathVariable Integer id) { (1)

    users.remove(id);

    }

    (1) PathVariable是Spring 的注解,对于这种简单的参数,就可以不用写ApiParam来描述接口参数。

    数组的描述

    @ApiOperation(value="删除用户-传递数组", notes="删除对象,传递数组")

    @RequestMapping(value="/users/deleteByIds", method = RequestMethod.DELETE)

    public void deleteUser(@ApiParam("用户ID数组") @RequestParam Integer[] ids) { (1)

    for (int id:ids){

    users.remove(id);

    }

    }

    (1) 这里用ApiParam为数组参数添加描述

    1.4 可选配置

    在application.properties中加入以下配置,用于设置测试请求的host,默认在swagger ui上做请求测试时都是以/users/1为路径发送请求。

    如果需要改变请求的根路径,就需要配置这个参数:

    springfox.documentation.swagger.v2.host = yourapp.abc.com

    配置获取api docs json数据的请求路径 ,默认为/v2/api-docs:

    springfox.documentation.swagger.v2.path = /api

    2. springfox-staticdocs 生成静态文档

    springfox

    2.1 Maven 配置

    io.springfox

    springfox-staticdocs

    2.2.2

    test

    2.2 生成json文件

    编写Junit测试,这样在测试环节就可以将api-docs的json数据写入文档,便于下一步生成asciidoc文件。

    @WebAppConfiguration

    @RunWith(SpringJUnit4ClassRunner.class)

    @SpringBootTest(classes = DemoBootApplication.class)

    public class Swagger2MarkupTest {

    @Autowired

    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before

    public void setUp() {

    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();

    }

    @Test

    public void createSpringfoxSwaggerJson() throws Exception {

    String outputDir = "src/docs/json"; //将api-docs的json数据写入文件

    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")

    .accept(MediaType.APPLICATION_JSON))

    .andExpect(status().isOk())

    .andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();

    String swaggerJson = response.getContentAsString();

    Files.createDirectories(Paths.get(outputDir));

    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)) {

    writer.write(swaggerJson);

    }

    }

    }

    2.3 配置Maven Plugin

    配置以下两个插件:

    swagger2markup-maven-plugin,该插件将json文件转为asciidoc

    asciidoctor-maven-plugin, 该插件将asciidoc转为html/pdf

    执行Maven命令 : mvn swagger2markup:convertSwagger2markup process-resources

    生成的html文档存储在src\main\resources\META-INF\resources\docs目录下。

    启动DemoBootApplication,直接访问http://localhost:8080/docs/index.html。

    jcenter-snapshots

    jcenter

    http://oss.jfrog.org/artifactory/oss-snapshot-local/

    false

    jcenter-releases

    jcenter

    http://jcenter.bintray.com

    io.github.swagger2markup

    swagger2markup-maven-plugin

    ${swagger2markup.plugin.version}

    io.github.swagger2markup

    swagger2markup-import-files-ext

    ${swagger2markup.extension.version}

    io.github.swagger2markup

    swagger2markup

    ${swagger2markup.version}

    ${swagger.input}

    ${generated.asciidoc.directory}

    ASCIIDOC

    TAGS

    generate-sources

    convertSwagger2markup

    org.asciidoctor

    asciidoctor-maven-plugin

    1.5.3

    org.asciidoctor

    asciidoctorj-pdf

    1.5.0-alpha.11

    org.jruby

    jruby-complete

    ${jruby.version}

    org.asciidoctor

    asciidoctorj

    ${asciidoctorj.version}

    展开全文
  • * @Description swaggerui * @since 2020/08/10 */ @EnableSwagger2 @Configuration public class BaseSwagger { @Autowired private Environment env; @Bean public Docket createRestApi() { String ...
    /**
     * @author Be.insighted
     * @Description swaggerui
     * @since 2020/08/10
     */
    @EnableSwagger2
    @Configuration
    @EnableSwaggerBootstrapUI
    public class BaseSwagger {
    
        @Autowired
        private Environment env;
    
        @Bean
        public Docket createRestApi() {
            String packagePath = env.getProperty("swagger.package");
            return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                            // 扫描的路径,Controller所在的包
                            .select().apis(RequestHandlerSelectors.basePackage(packagePath)) 
                            .paths(PathSelectors.any()) // PathSelectors.ant("URL Pattern")
                            .build();
        }
    
        private ApiInfo apiInfo() {
            String title = env.getProperty("swagger.title");
            String description = env.getProperty("swagger.description");
            String version = env.getProperty("swagger.version");
            return new ApiInfoBuilder().title(title).description(description).version(version).build();
        }
    }

    pom.xml中引入依赖

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${swagger.version}</version>
    </dependency>
    
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${swagger-ui.version}</version>
    </dependency>
    <dependency> 
        <groupId>com.github.xiaoymin</groupId> 
        <artifactId>swagger-bootstrap-ui</artifactId> 
        <version>1.9.6</version> 
    </dependency>

    application.yml

    使用时直接在浏览器中输入:http://host:port/swagger-ui.html

    方法一:禁用(指定环境下生效,指定配置文件)加上注解@Profile({"dev","test"})与@Configuration一起使用

    指定后

    方法二:配置文件中swagger.enable = false、然后配置类加上注解

    @ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
    # 接口文档
    swagger:
      author: 作者
      title: 你的标题
      package: controller层所在的文件夹路径,需是.而不是斜杠/ #API扫包
      version: 1.0
      description: 描述
      enable: 是否开启

     在下面的类上加上注解@EnableSwaggerBootstrapUI即可!

    效果:

    No operations defined in spec!

    处理: 配置文件中的package需是controller所在的路径,将斜杠/换成. 即可!

    swagger一些常用注解
             @Api:用在类上,说明该类的作用
             @ApiOperation:用在方法上,说明方法的作用
             @ApiIgnore:使用该注解忽略这个API
             @ApiImplicitParams:用在方法上包含一组参数说明
             @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
                paramType:参数放在哪个地方
                     header-->请求参数的获取:@RequestHeader
                     query-->请求参数的获取:@RequestParam
                     path(用于restful接口)-->请求参数的获取:@PathVariable
                     body(不常用)
                     form(不常用)
                 name:参数名
                 dataType:参数类型
                 required:参数是否必须传
                 value:参数的意思
                 defaultValue:参数的默认值
             @ApiResponses:用于表示一组响应
             @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
                 code:数字,例如400
                 message:信息,例如"请求参数没填好"
                 response:抛出异常的类
             @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
                @ApiModelProperty:描述一个model的属性 

    坑:引入 swagger-bootstrap-ui后,@ApiModelProperty,需将子标签required显示指为true,否则文档里会是否必须填充的是false!

    记不住访问url怎么破?重定向!

    @RestController
    @RequestMapping("/tool/swagger")
    public class SwaggerController extends BaseController {
        
        @GetMapping("/tool/swagger")
        public String index() {
            return redirect("/swagger-ui.html");
        }
    
        @GetMapping("/tool/doc")
        public String indexDoc() {
            return redirect("/doc.html");
        }
    }
    
    

    展开全文
  • swagger 微服务In previous postswe learned how to create a microservice in a notebook using the Jupyter kernel gateway. This will be the foundation for today’s post where we will be creating a ...
  • 微服务项目swagger配置

    2020-03-13 15:50:16
    如需转载分享,请标明出处,且不用于盈利...微服务项目swagger配置 1.pom.xml依赖 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> ...
  • 使用 Zuul 聚合多个微服务Swagger 文档 使用 Zuul 聚合多个微服务Swagger 文档 在 Zuul 中进行聚合操作的原因是不想每次都去访问独立服务的文档,通过网关统一整合这些服务的文档方便使用。 在网关中加入 ...
  • 单体项目的Swagger整合比较好整合,直接导入依赖即可,但是分布式或者微服务的项目整合就要稍微麻烦一点! 1.抽离出公共模块Common 提供给其他的模块使用,因为考虑到分布式和微服务有多个服务器,所以这里就同一...
  • SpringCloud+Mybatis的集成1、环境搭建1.1.顶级父工程 hrm_parent1.2.Eureka...系统管理微服务集成swagger4.zuul整合Swagger 1、环境搭建 1.1.顶级父工程 hrm_parent <properties> <project.build.sou...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 10,714
精华内容 4,285
关键字:

微服务之swagger