1.添加swagger依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2.和主类Application平级,创建类
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 org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
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 java.util.ArrayList;
//http://localhost:8080/swagger-ui.html
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
public static final Contact DEFAULT_CONTACT = new Contact("作者姓名", "作者号码", "作者邮箱");
@Bean
public Docket docket(Environment environment) {
// 获取yaml propertis中的环境状态代码(即spring.profiles.active)
Profiles profiles=Profiles.of("dev");
boolean b=environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.groupName("zyk")
// 配置项目标题,描述等信息
.apiInfo(apiInfo())
// 关闭swagger,如果为false,则不能在浏览器中访问swagger
.enable(b)
// 扫描特定的包中的controller
// .select().apis(RequestHandlerSelectors.basePackage("com.example.port8080.controller")).build()
// 扫描具有某个注解的类
.select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).build()
// 扫描方法上具有某个注解的类
.select().apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
// 扫描具有某个路径的类
.paths(PathSelectors.ant("/demo1/**"))
.build()
;
}
@Bean
public Docket docket2() {
return new Docket(DocumentationType.SWAGGER_2).groupName("zf");
}
@Bean
public Docket docket3() {
return new Docket(DocumentationType.SWAGGER_2).groupName("zzz");
}
public ApiInfo apiInfo() {
return new ApiInfo("标题",
"描述",
"版本号",
"官方网站",
DEFAULT_CONTACT,
// 开源版本协议
"Apache 2.0",
// 开源版本协议地址
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("学生实体类")
public class Student {
@ApiModelProperty("用户名")
public String username;
@ApiModelProperty("密码")
public String password;
}
@RestController
public class Demo2Controller {
@Autowired
Demo2pro demo2pro;
@ApiOperation("Demo2Controller控制类的getname方法")
@RequestMapping("/hello2")
public String getName(@ApiParam("学生姓名") String studentname) {
return demo2pro.getName()+demo2pro.getStudent();
}
}
在springboot2.6之后的版本使用swagger 需要添加如下配置 spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER