• 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

     

     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

    作者:CodingPanda
    座中铭:润物细无声,功到自然成
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    PHP $_POST 变量
    PHP $_GET 变量
    PHP 完整表单实例
    PHP 表单
    PHP 表单
    PHP 表单验证
    00_前情回顾
    18_今日回顾
    VMware 12PRO安装Mac OS X 10.10.5
    05_传智播客iOS视频教程_第一个OC程序
  • 原文地址:https://www.cnblogs.com/LiLiliang/p/15026884.html
Copyright © 2020-2023  润新知