首页 > 编程语言 > 详细

5分钟 springboot 整合swagger2

时间:2018-05-17 23:40:54      阅读:236      评论:0      收藏:0      [点我收藏+]

springboot 整合swagger2

1.maven配置文件中添加依赖

<properties>
    <swagger2.version>2.2.2</swagger2.version>
</properties>
--------------------------------------------------
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger2.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger2.version}</version>
</dependency>

2.添加SwaggerConfig.java 文件

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Value("${server.context-path}")
    private String pathMapping;

    @Bean
    public Docket createRestApi() {
        System.out.println("https://localhost:8443" + pathMapping + "/swagger-ui.html");
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("test")
                .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false)
                .pathMapping(pathMapping)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.weapp.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("标题")
                .description("描述")
                .termsOfServiceUrl("服务条款网址")
                .contact("justubborn")
                .version("1.0")
                .build();
    }

3.配置静态资源映射WebMvcConfig.java

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

4.在接口中使用swagger注解(参考官方文档)

@RestController
@RequestMapping
public class AppUserController {

    @Api(name=ApiConstant.GET_USER)
    @RequestMapping(value = "/api/v1/user/{id}", method = RequestMethod.GET, produces = "application/json")
    public Map<String, String> get(@PathVariable String id){
        ImmutableMap<String, String> map = ImmutableMap.of("id", id);
        return map;
    }
}

5.访问https://localhost:8443/weapp/swagger-ui.html

5分钟 springboot 整合swagger2

原文:https://www.cnblogs.com/wubenhui/p/9053926.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!