亲宝软件园·资讯

展开

spring boot-2.1.16整合swagger-2.9.2 含yml配置文件的代码详解

夏天的雪scy 人气:0

本文着重讲解了spring boot-2.1.16整合swagger-2.9.2 含yml配置文件,文中会用代码示例为大家做详细介绍,希望能够帮助到您,欢迎大家阅读和收藏

java代码

package com.oauth.util;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
//是否开启swagger
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {

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

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				// 页面标题
				.title("Swagger2")
				// 创建人信息
				.contact(new Contact("scy", "666", "888"))
				// 版本号
				.version("1.0")
				// 描述
				.description("API 描述").build();
	}
}

yml文件

server:
 port: 8587

spring:
 application:
  name: auth
  
eureka:
 instance:
  prefer-ip-address: true
 client:
  service-url:
   defaultZone: http://localhost:8090/eureka/
   
swagger:
 enable: true

swagger:
enable: true 这里是设置是否启动 本地和测试环境为true 正式环境为false

controller

package com.oauth.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("api")
@Api(value = "测试接口", tags = "IndexController")
public class IndexController {

	@ApiOperation(value = "hello")
	@GetMapping("hello")
	public String hello() {
		return "Hello World";
	}

	@ApiOperation(value = "hello2")
	@GetMapping("api/hello")
	public String apiHello() {
		return "Hello World";
	}

}

打开swagger页面 localhost:端口号/swagger-ui.html

在这里插入图片描述

如果swagger:
enable: false 这里设置为false

在这里插入图片描述

总结

加载全部内容

相关教程
猜你喜欢
用户评论