SpringBoot+Swagger2实现API文档+lombok工具包简化代码

Swagger UI:提供了一个可视化的UI页面展示描述文件。
接口的调用方、测试、项目经理等都可以在该页面中对相关接口进行查阅和做一些简单的接口请求。
该项目支持在线导入描述文件和本地部署UI项目。
lombok是一个可以帮助我们简化java代码编写的工具类,尤其是简化javabean的编写,
即通过采用注解的方式,消除代码中的构造方法,getter/setter等代码,使我们写的类更加简洁

1、在项目中的pom.xml文件中加入maven依赖包

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.8.0</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.8.0</version>
		</dependency>
		<!--lombok一个帮助我们简化javabean代码编写的工具包-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.6</version>
			<scope>provided</scope>
		</dependency>

2、添加Swagger配置类Swagger2Config

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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;

@Configuration
// 可指定配置文件,比如当使用prod生产环境的配置文件时该类不生效
@Profile({"dev", "test"})
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 为当前控制层包路径
                .apis(RequestHandlerSelectors.basePackage("com.tool.controller"))
                .paths(PathSelectors.any())
                .build();
    }
	
    /**
     * 构建 api文档的详细信息函数
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 页面标题
                .title("用户模块服务")
                // 描述
                .description("接口文档")
                .version("1.0")
                .build();
    }
}

3、在controller类中加上相应的注解

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RestController;

// @Api注解是swagger里的,主要为类提供相关说明
@Api(tags = "人员控制层接口")
@RestController
@RequestMapping("/v1/user")
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * @ApiOperation注解是swagger里的,主要为接口提供相关说明
	 */
	@ApiOperation(value = "根据工号查看人员详情")
	@PostMapping("/findUserDetailById")
	public ResultDto findUserDetailById(@RequestParam("userId") String userId) {
		return userService.findUserDetailById(userId);
	}
	
}

4、在启动类中加入@EnableSwagger2注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	
}

启动项目后,访问http://localhost:8080/swagger-ui.html 看看显示效果:出现下面页面则成功

当项目的静态文件路径被修改后,就会发生访问不到的情况

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Aug 01 09:50:09 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available

因为swagger-ui.html 是在springfox-swagger-ui.jar里的,
因为修改了路径Spring Boot不会自动把/swagger-ui.html这个路径映射到对应的目录META-INF/resources/下面。
所以我们修改SpringBoot配置类,为Swagger建立新的静态文件路径映射就可以了

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

@Configuration
@EnableWebMvc
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/");
    }
}

可以在实体类的类名上加入@ApiModel,变量使用@ApiModelProperty

@ApiModel作为类的描述
@ApiModelProperty作为字段的描述
@Data 注解相当于 Getter + Setter + ToString + @RequiredArgsConstrutor
需要注意的是:@ApiModel内的注释不要出现相同否则会将相同的vo内的字段进行合并

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

@ApiModel(value = "User", description = "人员信息描述")
@Data
public class User {
    
    @ApiModelProperty("工号")
    private String userId;
    
    @ApiModelProperty("姓名")
    private String userName;
    
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值