SpringBoot配置Swagger3(含源码)

1.在pom.xml中添加依赖包

        <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

2.添加swagger配置文件

package com.llltony.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * 基于Swagger生成API文档
 *
 * @EnableOpenApi:启动OpenApi的类
 * @author: lll
 */
@Configuration
@EnableOpenApi
public class SwaggerConfiguration {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.llltony.springboot.controller")).paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("Tsl API文档").description("Tsl API文档")
//                .contact(new Contact("联系人", "www.baidu.com", "286279186@qq.com"))
                .version("1.0").build();
    }

}

3.在bean文件中添加对应的swagger注解ApiModel和ApiModelProperty

package com.llltony.springboot.bean;

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

import java.io.Serializable;
import java.util.List;
@ApiModel(value = "EmployeeVo", description = "EmployeeVo类")
public class EmployeeVo implements Serializable {

    @ApiModelProperty(value = "员工队列")
    List<Employee>  employeeLst;

    public void setEmployeeLst(List<Employee> employeeLst) {
        this.employeeLst = employeeLst;
    }

    public List<Employee> getEmployeeLst() {
        return employeeLst;
    }
}

4.在controller中添加swagger注解Api和ApiOperation

package com.llltony.springboot.controller;


import com.llltony.springboot.bean.Employee;
import com.llltony.springboot.bean.EmployeeVo;
import com.llltony.springboot.bean.ResultMap;
import com.llltony.springboot.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/employee")
@Api(tags = "员工")
public class EmployeeController {

    @Resource
    EmployeeService employeeService;

    @Resource
    RabbitTemplate rabbitTemplate;

    //增加学生
    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ApiOperation(value="增加学生",notes = "增加学生信息")
    public ResultMap saveEmp(@RequestBody EmployeeVo employeeVo) {
        ResultMap resultMap = new ResultMap();
        try {
            employeeService.saveEmp(employeeVo);
            resultMap.setStatus("200");
            resultMap.setMessage("保存成功");
        } catch (Exception e) {
            resultMap.setStatus("500");
            resultMap.setMessage("保存失败");
        }
        return resultMap;
    }

    //通过消息队列异步增加学生
    @RequestMapping(value = "/addRebbitMq", method = RequestMethod.POST)
    @ApiOperation(value="通过消息队列异步增加学生",notes = "通过消息队列异步增加学生")
    public ResultMap addRebbitMq(@RequestBody EmployeeVo employeeVo) {
        ResultMap resultMap = new ResultMap();
        try {
            String messageId = String.valueOf(UUID.randomUUID());
            String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Map<String, Object> map = new HashMap<>();
            map.put("messageId", messageId);
            map.put("messageData", employeeVo);
            map.put("createTime", createTime);
            //将消息携带绑定键值:TestDirectRouting 发送到交换机TestDirectExchange
            rabbitTemplate.convertAndSend("EmployeeDirectExchange", "EmployeeDirectRouting", map);
//            employeeService.saveEmp(employeeVo);
            resultMap.setStatus("200");
            resultMap.setMessage("保存成功");
        } catch (Exception e) {
            resultMap.setStatus("500");
            resultMap.setMessage("保存失败");
        }
        return resultMap;
    }

    //删除学生
    @DeleteMapping("/{ids}")
    @ApiOperation(value="删除学生",notes = "删除学生")
    public ResultMap delEmp(@PathVariable("ids") String ids) {
        ResultMap resultMap = new ResultMap();
        try {
            employeeService.delEmp(ids);
            resultMap.setStatus("200");
            resultMap.setMessage("删除成功");
        } catch (Exception e) {
            resultMap.setStatus("500");
            resultMap.setMessage("删除失败");
        }
        return resultMap;
    }

    //查询学生
    @GetMapping("/{id}")
    @ApiOperation(value="查询学生",notes = "查询学生")
    public Employee getEmp(@PathVariable("id") Integer id) throws IOException {
        return employeeService.getEmpById(id);
    }

    //查询所有的学生
    @GetMapping("/getAll")
    @ApiOperation(value="查询所有的学生",notes = "查询所有的学生")
    public List<Employee> getAllEmp() {
        return employeeService.getAllEmp();
    }

    //修改学生
    @PutMapping("/")
    @ApiOperation(value="修改学生",notes = "修改学生")
    public ResultMap updateEmp(@RequestBody Employee employee) {
        ResultMap resultMap = new ResultMap();
        try {
            employeeService.updateEmp(employee);
            resultMap.setStatus("200");
            resultMap.setMessage("保存成功");
        } catch (Exception e) {
            resultMap.setStatus("500");
            resultMap.setMessage("保存失败");
        }
        return resultMap;
    }
}

5.配置完成,在浏览器中请求:http://127.0.0.1:8181/swagger-ui/index.html

 

 

 SpringBoot配置Swagger3(含源码)

 

 

 6.注意事项

如果使用了默认的访问静态配置:static-locations: classpath:html,会导致访问swagger报错。

解决这个问题需要自己重写静态资源访问方法,代码如下:

package com.llltony.springboot.config;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

public class WebConf extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //映射static路径的请求到static目录下
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }
}

7.资源

源码:https://github.com/CodingPandaLLL/tsl.git

 

上一篇:springboot 实现微信小程序(微信支付)


下一篇:mysql的两张表有两个且两张表都有两个主键时,mybatis需要resultMap需要调整