SpringBoot整合Swagger2,Swagger2的简单使用

第一章:Swagger使用之Swagger2


1. 注解解释

	@Configuration 
	 该注解的使用是让Spring来加载该类的配置
	
	@Bean 
	 注解是一个方法注解,它一般使用在@Configuration注解的类里面,它就是spring xml文件里面的bean
	
	@EnableConfigurationProperties(SwaggerProperties.class) 
	 该注解是让@ConditionalOnProperty注解类生效
	 当@EnableConfigurationProperties注解应用到你的@Configuration时, 
	 任何被@ConfigurationProperties注解的beans将自动被Environment属性配置
 
    @ConfigurationProperties("demo.swagger") 
	 该注解作用是进行赋值,和@Value类似,@Value是单个赋值,而@ConfigurationProperties多个赋值
     
	@ConditionalOnProperty(value = "demo.swagger.base-package")
	 该注解主要是控制@Configuration某个属性是否生效,也就是在去读取xx.properties或xx.yml文件里面对应的值,
	 若文件中有值则生效赋值,返回true,无就表示无效,返回false@ConditionalOnMissingBean(Docket.class) 
     该注解表示当@Conditional注解不满足条件,即不存在时将 @ConditionalOnMissingBean标注的类注入。
     换句话说就是它是备胎。正主在它没有任何作用,正主不在它才能起到作用。
     
    @EnableSwagger2 表示启用Swagger2

2.swagger依赖

//最新版本号自行查询
<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.8.0</version>
</dependency>

3.配置类

@Configuration
@EnableSwagger2
public class Swagger2Config(){
	@Bean
	public Docket createRestApi(){
		return new Docket(DocumentationType.SWAGGER_2)
				//创建该Api接口的基本信息,这些信息都会显示在文档页面
				.apiInfo(apiInfo()) 
				//调用该方法ApiSelectorBuilder对象,该对象用来控制那些接口暴露给Swagger,扫描了包,则表示所有的Controller接口都会暴露。
				.select() 
				//返回值ApiSelectorBuilder,设定扫描的包目录 
				.apis(RequstHandleSelectors.basePackage("com.zl.web"))
				//返回值ApiSelectorBuilder
				.paths(PathSelectors.any())
				.build()
				//把Date类型转化为String类型
				.directModelSubstitute(Date.class, String.class)
				.genericModelSubstitutes(ResponseEntity.class)
				.forCodeGeneration(true);;
	}
}

	//创建该Api的基本信息,这些基本信息都会展现在文档页面
	private ApiInfo apiInfo( ) {
    		return new ApiInfoBuilder()
            		.title("Spring Boot中使用Swagger2构建RESTful APIs") //标题
            		.description("描述信息")//例:©2019 Copyright. Powered By zl
            		.termsOfServiceUrl("http://blog.didispace.com/") //服务网址
            		.contact("黎子爱发呆")//联系人
            		.version("1.0")
            		.build();
}

/************************************* 实际例子1 *****************************************/

package com.mybatisplus.demo.mybatis.config;

import io.swagger.models.Response;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
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;

import java.util.Date;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                /**使用ApiSelectorBuilder对象,是用来控制将那些接口暴露给Swagger
                 * 扫描包表示所有接口都会暴露
                 * **/
                .select()
                //项目包路径
                .apis(RequestHandlerSelectors.basePackage("com.mybatisplus.demo.mybatis"))
                .paths(PathSelectors.any())
                .build()
                //把时间类型转换成String类型
                .directModelSubstitute(Date.class,String.class)
                .genericModelSubstitutes(Response.class)
                .forCodeGeneration(true);
    }
    
    //创建该Api的基本信息,这些基本信息都会展现在文档页面
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("swagger2测试")
                .description("接口测试")
                //服务器网址
                .termsOfServiceUrl("http:localhost:8080/")
                .version("1.0")
                .build();
    }
}

在这里插入图片描述


/************************************* 实际例子2 *****************************************/

package com.mybatisplus.demo.mybatis.config.swagger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;

    @Bean
    @ConditionalOnProperty(value = "demo.swagger.base-package")
    @ConditionalOnMissingBean(Docket.class)
    public Docket autoEnableSwagger() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerProperties.getEnabled())
                .apiInfo(apiInfo(new ApiInfoProperties()))
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(PathSelectors.any())
                .build()
                .globalRequestParameters(params())
                .directModelSubstitute(Date.class, String.class)
                .genericModelSubstitutes(Result.class)
                .forCodeGeneration(true);
    }

    private ApiInfo apiInfo(ApiInfoProperties apiInfo) {

        if(apiInfo == null) {
            return new ApiInfoBuilder().build();
        }

        return  new ApiInfoBuilder()
        		.title(apiInfo.getTitle())
                .description(apiInfo.getDescription())
                .contact(new Contact(apiInfo.getContact(),apiInfo.getUrl(), apiInfo.getEmail()))
                .version(apiInfo.getVersion())
                .build(); 
    }

	//全局参数设置
    private List<Parameter> params(){
        List<Parameter> operationParameters = new ArrayList<>();
        operationParameters.add(new ParameterBuilder()
	        .name("u_id")
	        .parameterType("header")
	        .modelRef(new ModelRef("String"))
	        .required(false)
	        .build());
        operationParameters.add(new ParameterBuilder()
	        .name("u_type")
	        .parameterType("header")
	        .modelRef(new ModelRef("String"))
	        .required(false)
	        .build());
        operationParameters.add(new ParameterBuilder()
	        .name("authority")
	        .parameterType("header")
	        .modelRef(new ModelRef("String"))
	        .required(false).build());
        return operationParameters;
    }
}


/************************************* SwaggerProperties *****************************************/

package com.mybatisplus.demo.mybatis.config.swagger;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("demo.swagger")
public class SwaggerProperties {

    private boolean enabled = false;
    private String basePackage;
    private ApiInfoProperties apiInfo;

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getBasePackage() {
        return basePackage;
    }

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }

    public ApiInfoProperties getApiInfo() {
        return apiInfo;
    }

    public void setApiInfo(ApiInfoProperties apiInfo) {
        this.apiInfo = apiInfo;
    }
}

//注解解释:

4. yml.xml文件配置(👆)

在这里插入图片描述

5.实体类使用

@Data
@ApiModel(value = "用户", description = "用户")
public class User implements Identifiable<Long> {

    @ApiModelProperty(value = "用户id")
    private Long id;

    @ApiModelProperty(value = "用户姓名")
    private String name;

    @ApiModelProperty(value = "用户性别,1-男 0-女")
    private Integer sex;

    @ApiModelProperty(value = "用户昵称")
    private String nickName;

    @ApiModelProperty(value = "用户手机号")
    private String mobile;

    @ApiModelProperty(value = "用户密码")
    @JsonIgnore
    private String password;

    @ApiModelProperty(value = "用户状态,1=正常,0=禁用")
    private Integer state;

    @ApiModelProperty(value = "用户头像")
    private String image;
}

6.Controller使用

@RestController
@RequestMapping(value = "/web/user")
@Api(description = "用户")
public class UserController { 
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation(value = "登录", notes = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "登录名", required = true, dataType = "java.lang.String", paramType = "form"),
            @ApiImplicitParam(name = "password", value = "登录密码", required = true, dataType = "java.lang.String", paramType = "form")
    })
    public Response login(String password, String username) {
        return Response.ok("登录成功", null);
    }
}

7.测试接口

启动项目,输入网址:localhost:8080/swagger-ui.html
在这里插入图片描述
点击运行
运行结果
其他swagger注解请参考

8.注意

swagger2在17年就停止更新了,现在已经升级到swagger3
【swagger3使用】

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值