package com.example.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("用户测试类")
public class User {
@ApiModelProperty("用户名")
public String name;//必须是public,前提是没加get 和 set
@ApiModelProperty("密码")
public String pwd;
}
controller
package com.example.controller;
import com.example.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String Hello(){
return "hello";
}
@ApiOperation("Hello1接受用户")
@PostMapping("/hello1")
public String Hello1(@ApiParam("用户名") String name ,@ApiParam("密码") String password){
return "你输入的用户名和密码分别是"+name+":"+password;
}
@ApiOperation("Hello2测试用户方法")//Operation只能用在方法上
@GetMapping("/hello2")//只要我们的放回值中存在实体类它就会被扫描到swagger中
public User getUser(){
return new User();
}
}
config
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
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 java.util.ArrayList;
@Configuration
public class SwaggerConfig {
// http://localhost:8080/swagger-ui/index.html新版路径
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("Text1");//配置多个组但是不要重名
}
@Bean//配置swagger的Docket bean实例
public Docket docket(Environment environment){
//设置当前要显示的Swagger环境
Profiles of = Profiles.of("dev", "text");
//获取当前项目环境
boolean b = environment.acceptsProfiles(of);
return new Docket(DocumentationType.SWAGGER_2)
.enable(b)//是否启用swagger是false 默认true
.apiInfo(apiInfo())
.select()
//RequestHandlerSelectors配置要扫描接口的方式
//any()扫描全部
//none()不扫描
//withClassAnnotation()扫描类上的注解,参数是一个注解的反射对象
//withMethodAnnotation()扫描方法上的注解
//basePackage()指定要扫描那个包
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
//.paths(PathSelectors.ant("/hello/**"))//过滤什么路径
.build()
.groupName("Hello")//配置分组
;
}
//配置swagger的一些信息 作者信息
public ApiInfo apiInfo(){
Contact contact = new Contact("鲁家见","","482475181@qq.com");
return new ApiInfo(
"L的swagger的API文档",
"学生管理项目文档",
"1.0",
"urn:tos",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>());
}
}