Springboot集成Swagger操作步骤以及数据注入

7 篇文章 0 订阅

Springboot集成Swagger操作步骤以及数据注入

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。
作用:

  1. 接口的文档在线自动生成。
  2. 功能测试。

基本配置

第一步:配置pom.xml

  <dependencies>
    ...
    <!-- swagger -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.5.0</version>
    </dependency>
    <!-- swagger-ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.5.0</version>
    </dependency>
  </dependencies>

第二步:IDEA执行Reimport All Maven Projects
第三步:使用注解来进行启动swagger

package com.template.swagger;

import springfox.documentation.service.Contact;
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.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by bianxh on 2019/1/21.
 */
@Configuration
@EnableSwagger2
public class SwaggerApp {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.template.controller"))
                .paths(PathSelectors.any())
                .build();
//        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("Spring Boot 使用 Swagger2 构建RESTful API")
                //创建人
                .contact(new Contact("Bryan", "http://blog.bianxh.top/", ""))
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}

第四步:配置Controller

package com.template.controller;
/**
 * @Description:
 * @Author: Bryan
 * @Date: 2018/12/29 18:15
 */
@Api(description = "用户操作接口")
@Controller("user")
@RequestMapping("/user")
public class UserController extends BaseController {
//...
    @ApiOperation(value = "获取otp", notes="通过手机号获取OTP验证码")
    @ApiImplicitParam(name = "telephone", value = "电话号码", paramType = "query", required = true, dataType = "Integer")
    @RequestMapping(value = "getotp", method=RequestMethod.GET)
    @ResponseBody
    public CommonReturnType getOtp(@RequestParam(name = "telephone") String telphone) {
        //需要按照一定的规则生成OTP验证码
        Random random = new Random();
        int randomInt = random.nextInt(99999);
        randomInt += 10000;
        String otpCode = String.valueOf(randomInt);

        //将OTP验证码同对应用户的手机号关,使用httpsession的方式绑定他的手机号与OTPCode
        httpServletRequest.getSession().setAttribute(telphone,otpCode);
        //将OTP验证码通过短信通道发送给用户,省略
        System.out.println("telphone = " + telphone + "& otpCode = " + otpCode);
        OtpVo otpVo = new OtpVo();
        otpVo.setTelephone(telphone);
        otpVo.setOtpCode(otpCode);
        return CommonReturnType.create(otpVo);
    }
//...
}

第五步:访问 http://localhost:8081/swagger-ui.html,可以看到如下效果

image-20200308223738990

接下来测试一下接口:

image-20200308223755439

注入配置文件数据

application.properties

#是否激活 swagger true or false
swagger.enable=true

解析yml文件的工具类

package com.facebook.rbac.utils;


import java.io.IOException;
import java.util.Optional;
import java.util.Properties;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

/**
 * CompositePropertySourceFactory support properties and yaml file
 *
 * @author Wang.ch
 * @date 2019-03-22 09:30:15
 */
public class CompositePropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource)
            throws IOException {
        String sourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        if (!resource.getResource().exists()) {
            // return an empty Properties
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYaml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    /**
     * load yaml file to properties
     *
     * @param resource
     * @return
     * @throws IOException
     */
    private Properties loadYaml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}

外层配置

package com.facebook.rbac.config;


import com.facebook.rbac.utils.CompositePropertySourceFactory;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;


/**
 * @author allen
 */
@PropertySource(value = "classpath:swagger.yml", factory = CompositePropertySourceFactory.class)
@ConfigurationProperties(prefix = "swagger")
@Data
public class SwaggerYml {
    private String title;
    private String description;
    private String version;
    private String termsOfServiceUrl;

    private SwaggerContactYml contact;
}


内层配置

package com.facebook.rbac.config;


import lombok.Data;

/**
 * @author allen
 */
@Data
public class SwaggerContactYml {

    private String name;
    private String url;
    private String email;


}

注入数据

package com.facebook.rbac.config;

import com.facebook.rbac.utils.CompositePropertySourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;

/**
 * @author allen
 */ //swagger2的配置文件,在项目的启动类的同级文件建立
@Configuration
@EnableSwagger2
//是否开启swagger,正式环境一般是需要关闭的(避免不必要的漏洞暴露!),可根据springboot的多环境配置进行设置
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
//@PropertySource(value = "classpath:swagger.yml",factory = CompositePropertySourceFactory.class)
//@ConfigurationProperties(prefix = "swagger")
@EnableConfigurationProperties(SwaggerYml.class)
public class SwaggerAppConfig {


    @Resource
    private SwaggerYml swaggerYml;

    // swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.facebook.rbac.api")).paths(PathSelectors.any())
                .build();
    }

    // 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 页面标题
                .title(swaggerYml.getTitle())
                // 创建人信息
//                .contact(new Contact(contactName, contactUrl, contactEmail))
                .contact(new Contact(swaggerYml.getContact().getName(),
                        swaggerYml.getContact().getUrl()
                        ,
                        swaggerYml.getContact().getEmail()))
                // 版本号
                .version(swaggerYml.getVersion())
                // 描述
                .description(swaggerYml.getDescription())
                .build();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Spring Boot集成Swagger的详细步骤与配置: 1. 在pom.xml文件中添加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.9.2</version> </dependency> ``` 2. 创建Swagger配置类 创建一个SwaggerConfig类,并使用@EnableSwagger2注解开启Swagger功能。在Swagger配置类中,可以设置Swagger的一些基本信息,比如API文档的标题、描述、版本等。 ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build(); } } ``` 3. 配置Swagger UI 在application.properties文件中添加以下配置,以开启Swagger UI: ``` #Swagger UI springfox.documentation.swagger-ui.enabled=true springfox.documentation.swagger-ui.path=/swagger-ui.html ``` 4. 配置Swagger注解 在Controller层的方法上添加Swagger注解,以便生成API文档。常用的Swagger注解有: - @Api:用于修饰Controller类,表示这个类是Swagger资源; - @ApiOperation:用于修饰Controller类中的方法,表示一个HTTP请求的操作; - @ApiParam:用于修饰方法中的参数,表示对参数的描述; - @ApiImplicitParam:用于修饰方法中的参数,表示一个请求参数的配置信息; - @ApiModel:用于修饰响应类,表示一个返回响应的信息,比如响应的数据模型; - @ApiModelProperty:用于修饰响应类中的属性,表示对属性的描述。 例如: ``` @RestController @Api(value = "用户管理", tags = "用户管理API", description = "用户管理相关接口") public class UserController { @ApiOperation(value = "获取用户列表", notes = "获取所有用户信息") @GetMapping("/users") public List<User> getUserList() { // ... } @ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户信息") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long") @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { // ... } } ``` 5. 运行程序并访问Swagger UI 启动Spring Boot项目后,在浏览器中输入http://localhost:8080/swagger-ui.html,即可访问Swagger UI界面。在该界面中,可以查看API接口的详细信息、测试API接口等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值