搭建springboot后端框架(四)集成swagger2

项目搭建工具及版本:

eclipse / jdk1.8 / springboot2.5.0 

1.pom.xml引入相关jar包

        <!-- fastjson-1.2.29.jar -->
        <dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>1.2.29</version>
		</dependency>
		
		<!-- swagger2 -->
    	<dependency>
		    <groupId>io.springfox</groupId>
		    <artifactId>springfox-swagger2</artifactId>
		    <version>2.9.2</version>
		</dependency>
		<!-- swagger-ui -->
		<dependency>
		    <groupId>io.springfox</groupId>
		    <artifactId>springfox-swagger-ui</artifactId>
		    <version>2.9.2</version>
		</dependency>
		<!-- commons -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>

2.application.properties增加是否开启swagger的开关

#===================== swagger配置 ===================== 
#swagger启停开关
swagger.enabled=true

3.增加swagger配置类

package com.bbnet.config.swagger2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import io.swagger.annotations.ApiOperation;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config {
	
	protected final Logger log = LoggerFactory.getLogger(Swagger2Config.class);
	
	/** 是否开启swagger */
    @Value("${swagger.enabled}")
    private boolean enabled;
	
    /**
	*
	* 显示swagger-ui.html文档展示页,还必须注入swagger资源:
	*
	* @param registry
	*/
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    	registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
    	registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    
    /**
     * 创建一个Docket对象
     * 调用select()方法,
     * 生成ApiSelectorBuilder对象实例,该对象负责定义外漏的API入口
     * 通过使用RequestHandlerSelectors和PathSelectors来提供Predicate,在此我们使用any()方法,将所有API都通过Swagger进行文档管理
     * @return
     */
    @Bean
    public Docket createRestApi() {
    	log.info("Swagger2配置初始化完成");
        return new Docket(DocumentationType.SWAGGER_2)
        		//是否启用Swagger
                .enable(enabled)
                //用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo(apiInfo())
                //设置哪些接口暴露给Swagger展示
                .select()
                //扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //扫描指定包中的swagger注解
                .apis(RequestHandlerSelectors.basePackage("com.bbnet"))
                //扫描所有
                //.apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
    	//用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                //标题
                .title("BBnet后台系统接口API")
                //简介
                .description("")
                //服务条款
                .termsOfServiceUrl("")
                //版本
                .version("1.0")
                .build();
    }
}
package com.bbnet.config.swagger2;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class Swagger2WebMvcConfig implements WebMvcConfigurer {
	
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决 swagger-ui.html 404报错
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    
}

4.vo/controller使用swagger注解示例

package com.bbnet.demo.vo;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;


@Data
@Accessors(chain = true)
@TableName("ht_area")
@ApiModel(value="Demo对应的Area实体")
public class Area {

	@ApiModelProperty(value = "主键id")
	@TableId
    private Integer id;
	
	@ApiModelProperty(value = "名称")
    private String name;
    
    @ApiModelProperty(value = "父级id")
    private Integer parentId;
    
    @ApiModelProperty(value = "类型 1=省会/直辖市 2=城市 3=区县")
    private Integer type;

}
package com.bbnet.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.service.IService;
import com.bbnet.common.base.BaseController;
import com.bbnet.demo.service.AreaService;
import com.bbnet.demo.vo.Area;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/demo")
@Api(tags = "该类的功能描述")
public class DemoController extends BaseController<Area> {
	
	private static final Logger log = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private AreaService areaService;

	@Override
	public IService<Area> getIService() {
		return areaService;
	}
	
	@ApiOperation(value="该方法的功能描述", notes="该方法更详细的使用描述TODO")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "String")
	})
    @PostMapping("/catchReq")
    public String catchReq(@RequestParam String id) {
    	log.info("初始化了getIService...");
    	return areaService.say();
    }
	
	
}

5.swagger测试示例

 请求地址http://127.0.0.1:8888/bbnet/swagger-ui.html可访问swagger页面

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cgv3

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值