1.引入依赖
<!-- swag包--> <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.配置类
@Configuration @EnableSwagger2//开启 public class SwagConfig { //配置了Swag的Docket的bean实例 @Bean public Docket docket(Environment environment){ //配置在生产环境中使用但是在发布环境不使用 //设置要显示的swagger环境 Profiles profiles=Profiles.of("dev"); //获取项目的环境 boolean flag = environment.acceptsProfiles(profiles);//为true就表示现在的环境是dev System.out.println(flag); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(getApiInfo()) .groupName("吴某") .enable(flag)//是否启用swagger .select() //指定要扫描的包 any()扫描全部 none()都不扫描 //withClassAnnotation:扫描类上的注解 //withMethodAnnotation()扫描方法上的注解 .apis(RequestHandlerSelectors.basePackage("com.wu.controller")) //过滤什么路径 //.paths(PathSelectors.ant("/meiyou/**")) .build(); } private ApiInfo getApiInfo(){ Contact contact=new Contact("小吴","https://home.cnblogs.com/u/*min/","565482647@qq.com"); return new ApiInfo("小吴的swagger日记", "宇智波", "1.0", "https://home.cnblogs.com/u/*min/", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } //配置多个docket实例每个代表一个不同的组 @Bean public Docket docket1(){ return new Docket(DocumentationType.SWAGGER_2).groupName("A"); } @Bean public Docket docket2(){ return new Docket(DocumentationType.SWAGGER_2).groupName("B"); } }
3.进入面板
4.用在实体类上的注解
@ApiModel("用户实体类") public class User { @ApiModelProperty("用户名") public String username; @ApiModelProperty("密码") public String password; }
5.HelloController
@RestController public class HelloController { @GetMapping(value = "/hello") public String hello(){ return "hello"; } @PostMapping(value="/user")//只要我们的接口中返回值存在实体类就会被扫描到 public User user(){ return new User(); } @ApiOperation("hi控制类") @GetMapping(value="/hi") public String hi(@ApiParam("用户名") String username){ return "hi"+username; } @ApiOperation("post控制类") @PostMapping(value="/postt") public User postt(@ApiParam("用户名") User user){ return user; } }
6.多个环境的配置
7.可以在ui里进行测试