spring boot2 swagger
时间: 2023-10-28 11:05:36 浏览: 104
Spring Boot是一个基于Spring框架的快速开发框架,而Swagger是一个API文档生成工具,可以方便地生成API文档并进行测试。在Spring Boot中集成Swagger可以方便地生成API文档,提高开发效率。
要在Spring Boot中集成Swagger,需要在pom.xml文件中添加Swagger的依赖,然后在启动类上添加@EnableSwagger2注解即可。接着,在Controller层的方法上添加@Api和@ApiOperation注解,即可生成API文档。
相关问题
spring boot 集成swagger3
好的,关于集成Swagger3,你可以按照以下步骤进行操作:
1. 在pom.xml文件中添加Swagger3的依赖:
```xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
```
2. 在Spring Boot的启动类上添加`@EnableSwagger2`注解:
```java
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
3. 创建Swagger配置类,配置Swagger相关信息:
```java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot集成Swagger3")
.description("Spring Boot集成Swagger3示例")
.version("1.0")
.build();
}
}
```
4. 启动应用程序,访问`http://localhost:8080/swagger-ui/index.html`即可查看API文档。
Spring Boot 禁用 Swagger
在 Spring Boot 项目中,可以通过添加配置来禁用 Swagger。
1. 针对整个应用禁用 Swagger
可以在应用的 `application.properties` 文件中添加以下配置:
```properties
springfox.documentation.enabled=false
```
或者在应用的启动类上添加 `@EnableSwagger2` 注解,并重写 `addResourceHandlers` 方法,将 Swagger UI 的访问路径重定向到 `/error`:
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/")
.setCachePeriod(0);
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(0);
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod(0);
registry.addResourceHandler("/swagger-resources/**")
.addResourceLocations("classpath:/META-INF/swagger-resources/")
.setCachePeriod(0);
}
}
```
2. 针对指定的 API 禁用 Swagger
可以在 API 的实现类上添加 `@ApiIgnore` 注解,例如:
```java
@RestController
@RequestMapping("/api")
@ApiIgnore
public class MyController {
// ...
}
```
这样,Swagger 将不会显示该 API。