当前位置:网站首页>Swagger2 easy to use
Swagger2 easy to use
2022-06-11 18:39:00 【starriesWEB】
newly build springboot project , Check web, Import swagger rely on
<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>
To write controller
@Controller
public class MyController {
@RequestMapping("/hello")
@ResponseBody
public String hello(){
return "hello swagger";
}
}
To configure Swagger Information
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo("Swagger The title of the ",
"Swagger Description of ",
"2.0",
"https://blog.csdn.net/qq_45722508?type=blog",
new Contact("starry","https://blog.csdn.net/qq_45722508?type=blog","[email protected]"),
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>());
}
}
Start access , visit /hello, Normal return
visit http://localhost:8080/swagger-ui.html, The information is modified normally 
Configure scan interface and switch
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.apiInfo())
.select()
// RequestHandlerSelectors Configure how to scan
.apis(RequestHandlerSelectors.basePackage("com.starry.controller"))
// Path filtering Only scan the request path with /starry/**
// .paths(PathSelectors.ant("/starry/**"))
.build();
}
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.apiInfo())
// Cannot access from the browser swagger
.enable(false)
.select()
// RequestHandlerSelectors Configure how to scan
.apis(RequestHandlerSelectors.basePackage("com.starry.controller"))
// Path filtering Only scan the request path with /starry/**
// .paths(PathSelectors.ant("/starry/**"))
.build();
}
Give Way Swagger In production , Test environment , Don't use when publishing
To configure 3 An environment
- application-dev.properties
server.port=8081 - application-prod.properties
server.port=8082 - application-test.properties
server.port=8083
Judge the environment
@Bean
public Docket docket(Environment environment) {
// Set up swagger The environment to be opened
Profiles profiles = Profiles.of("dev","test");
// Determine whether the current environment of the project is the same as the specified environment
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.apiInfo())
// If it's production , The test environment starts swagger
.enable(flag)
.select()
// RequestHandlerSelectors Configure how to scan
.apis(RequestHandlerSelectors.basePackage("com.starry.controller"))
// Path filtering Only scan the request path with /starry/**
// .paths(PathSelectors.ant("/starry/**"))
.build();
}
application.properties
# Set up the current environment
spring.profiles.active=dev
Environment switch to dev,test All can be accessed normally swagger
Environment switch to prop, Cannot display document 
Configure packet and receive parameter types
.groupName("starry")
Configure multiple groups , Added Bean that will do
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}

Set the type passed in by the front end
.consumes(new LinkedHashSet<String>(Arrays.asList("application/json","application/xml","application/text")))

@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(Environment environment) {
// Set up swagger The environment to be opened
Profiles profiles = Profiles.of("dev","test");
// Determine whether the current environment of the project is the same as the specified environment
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.apiInfo())
// If it's production , The test environment starts swagger
.enable(flag)
// Set the type passed in by the front end
.consumes(new LinkedHashSet<String>(Arrays.asList("application/json","application/xml","application/text")))
.groupName("starry")
.select()
// RequestHandlerSelectors Configure how to scan
.apis(RequestHandlerSelectors.basePackage("com.starry.controller"))
// Path filtering Only scan the request path with /starry/**
// .paths(PathSelectors.ant("/starry/**"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfo("Swagger The title of the ",
"Swagger Description of ",
"2.0",
"https://blog.csdn.net/qq_45722508?type=blog",
new Contact("starry","https://blog.csdn.net/qq_45722508?type=blog","[email protected]"),
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>());
}
}
Interface notes
newly build User object
public class User {
private String username;
private String password;
//getter/setter
}
to controller Add notes to explain
@Api(tags = " User controller")
@RestController
public class MyController {
@ApiOperation(value = "hello")
@GetMapping("/hello")
@ApiResponses({
@ApiResponse(code = 500,message = " internal error "),@ApiResponse(code = 404,message = " Resource not found ")})
public String hello(@ApiParam(value = " user name ")String name){
// Make a deliberate mistake
int i = 1 / 0;
return "name";
}
@ApiOperation(value = " Query the user ")
@GetMapping("/getUser")
public User getUser(){
return new User("starry","starry");
}
@ApiOperation(value = " pick up information ")
@PostMapping("/postUser")
public User postUser(User user){
return user;
}
}
| annotation | describe |
|---|---|
| @Api() | tags = “ Document labels ”, consumes = “ Types accepted by the server ” |
| @ApiOperation | Interface specification |
| @ApiParam | Parameter description |
| @ApiResponses | Pass in @ApiResponse Array , Customize the status code and return information |


Annotate the entity class , Only controller The return value is User when , In the document Models It shows that
@ApiModel(description = " User details ")
public class User {
@ApiModelProperty(value = " user name ")
private String username;
@ApiModelProperty(value = " password ")
private String password;
}
| annotation | describe |
|---|---|
| @ApiModel | description = “ A detailed description of the class ” |
| @ApiModelProperty | Description of the field |

边栏推荐
- 5 minutes to understand the red, blue and purple in the attack and defense drill
- 学习使用LSTM和IMDB评论数据进行情感分析训练
- 力扣31 下一个排列
- 牛客刷题——求最小公倍数
- 全志科技T3开发板(4核ARM Cortex-A7)——视频开发案例
- Quanzhi technology T3 development board (4-core arm cortex-a7) - mqtt communication protocol case
- H. 264 concept
- 牛客刷题——把字符串转换成整数
- 力扣33题,搜索旋转排序数组
- Dynamic explosion effect
猜你喜欢

金融银行_催收系统简介

BigDecimal基本使用与闭坑介绍
![[c language] output the average score and the student data below or equal to the average score with the structure](/img/c4/263301a22b61c86a3e0df6ad2596f1.png)
[c language] output the average score and the student data below or equal to the average score with the structure

H. 264 concept

The nearest common ancestor of binary tree

* Jetpack 笔记 Room 的使用

2023年西安交通大学管理学院MPAcc提前批面试网报通知

Cool visualization tool: first introduction to processing

全志科技T3開發板(4核ARM Cortex-A7)——MQTT通信協議案例
开发中必备的文件的上传与下载
随机推荐
软件开发的整体流程
一款自适应的聊天网站-匿名在线聊天室PHP源码
Téléchargement et téléchargement des fichiers nécessaires au développement
Signal processing and capture
力扣刷题——二叉树的最近公共祖先
Ubuntu installs PSQL and runs related commands
* Jetpack 笔记 Room 的使用
SQL注入漏洞学习之一:phpstudy集成环境搭建DVWA靶场
JS实现全屏展示的具体方法
Ti am64x - the latest 16nm processing platform, designed for industrial gateways and industrial robots
Balanced search binary tree -- AVL tree
全志科技T3开发板(4核ARM Cortex-A7)——MQTT通信协议案例
金融银行_催收系统简介
5分钟了解攻防演练中的红蓝紫
H. 264 concept
如何在 SAP BTP 上 手动执行 workflow
新项目 搭建环境方法
*Jetpack notes understanding of lifecycle ViewModel and livedata
Force deduction 23 questions, merging K ascending linked lists
全国院校MBA、EMBA、MPA、MEM、提前面试(预面试)时间批次已出(持续更新中)-文都管联院