Spring Boot整合swagger

Spring Boot整合swagger

前言:为什么写swagger?
前端大佬要求,需要用这个框架,方便出现其他接口参数问题时,可以高效的沟通,当我修改完后端接口的时候。前端立马就知道应该怎么写了。
对我来说,工作量也没有增加很多。需要前期的一个配置,后期无论是什么接口,配上3个参数就行。有一点很方便,使用这个,我就不需要使用Postman了。节约了一个软件,美滋滋~~~

第一步,先上怎么写?
1.先在pom.xml中添加两个依赖


    io.springfox
    springfox-swagger2
    2.9.2


    io.springfox
    springfox-swagger-ui
    2.9.2

2.新建swaggerConfig.java类,配置相应的信息

package com.xxx.xxx.config;   //你的包名

import springfox.documentation.service.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.ArrayList;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.controller"))   //配置相应的控制类的包名
                .build();
    }
    /**
     * 配置swagger信息apiInfo这些信息是显示在界面上面的
     * */
    private ApiInfo apiInfo(){
        Contact contact = new Contact("xxx", "no", "1xxxxx");
        return new ApiInfo("xxx Api Swagger 文档",
                "Api文档",
                "1.0","no",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",new ArrayList());
    }
}

3.配置WebMvcConfig.java 类
允许外网的访问需要addResourceHandlers

package com.xxx.xxx.config;

import com.xxx.xxx.handler.SessionInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer{
    @Autowired
    private SessionInterceptor sessionInterceptor;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
                .allowCredentials(false).maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessionInterceptor).addPathPatterns("/getUserById","/getCurrentUser","/getCurrentUserByToken","/modifyUserInfo",
                "/travel/publish","/travel/update").excludePathPatterns("");
    }
}

接口应该怎么写?

1.Controller类写描述。用@Api的注解

@RestController
@RequestMapping("/travel")
@Api(description = "游记控制类",tags = "游记操作接口" )
public class TravelController {
    public static final String CURRENT_USER_SESSION = "currentUserSession";

2.对于每一个方法名用注解@ApiOperation,起到备注接口信息的作用

/**
 * 通过id获取User对象
 * **/
@GetMapping("/getUserById")
@ApiOperation("通过ID获取User对象")
public CommonRes getUserById(@RequestParam(name = "id")Integer id) throws BusinessException {
    User currentUser = (User) httpServletRequest.getSession().getAttribute(CURRENT_USER_SESSION);
    if(currentUser == null){
        throw new BusinessException(EmCommonError.PERMISSION_ERROR);
    }
    User user = userService.getUserById(id);
    if(user == null){
        throw new BusinessException(EmCommonError.NO_OBJECT_FOUND);
    }else {
        return CommonRes.create(currentUser);
    }
}

3.前端参数属性名ApiModelProperty ,备注属性名的作用

package com.xxx.xxx.request;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;

@Data
public class LoginReq {
    @NotBlank(message = "手机号不能为空")
    @ApiModelProperty("手机号")
    private String telephone;
    @NotBlank(message = "密码不能为空")
    @ApiModelProperty("密码")
    private String password;
}

接下来你就可以使用了:
http://127.0.0.1:8080/swagger-ui.html#/

你可能感兴趣的:(Spring Boot整合swagger)