@Configuration //加了这个注解就会配置到配置里面 @EnableSwagger2 //开启swagger public class SwaggerConfig { //配置swagger的Docket的Bean实例 @Bean public Docket docket(Environment environment){ //设置要显示的swagger环境 Profiles profile=Profiles.of("dev","txt"); //获取项目环境---通过environment.acceptsProfiles(profile);判断是否处于自己设定的环境当中 boolean flag=environment.acceptsProfiles(profile); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //对应下面那个方法,显示基本信息的 .enable(flag) //判断运行环境是否正确 .groupName("李泽宏")//api分组 groupName("李泽宏")右上角那个框框要显示的东西 .select() //RequestHandlerSelectors 配置要扫描接口的方式-- //enable(boolean) 是否启用swagger 如果为false则不在浏览器中显示 // basePackage是扫描哪个controller //any():扫描全部 // none():都不扫描 //withClassAnnotation(类名.class):扫描类上注解---参数是一个注解的反射对象 //.withMethodAnnotation():扫描方法上的注解 //PathSelectors.ant("/example/**")表示扫描example下面的 //表示扫描哪个控制器 .apis(RequestHandlerSelectors.basePackage("com.example.swaggerdemo.controller")) //paths:过滤什么路径 //.paths(PathSelectors.ant("/example/**")) .build(); } //配置swagger信息=apiInfo //@Bean public ApiInfo apiInfo(){ Contact contact=new Contact("李泽宏", "........", "2082620872@qq.com"); return new ApiInfo("李泽宏色情日记" //标题 , "花花世界迷人眼,没有实力别赛脸" //描述 , "1.0" //版本 , "...................." , contact , "Apache 2.0" , "http://www.apache.org/licenses/LICENSE-2.0" //提供的地址 , new ArrayList()); } }
控制层
@ApiOperation("控制类") //这个注解说明这是一个控制类 @RestController public class HelloController { @GetMapping("/hello") public String hello(){ return "hello"; } //只要我们接口中,返回值存在实体类中 他就会被扫描到 @PostMapping("/user") public User user(){ return new User(); } }
需要的依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>