java 单体若以框架swagger配置
时间: 2024-10-20 21:11:05 浏览: 68
在 Java 中,Swagger 是一款用于生成 API 文档和测试工具的流行库。若要在单体应用中配置 Swagger,通常会遵循以下步骤:
1. 添加依赖:首先,你需要在你的 Maven 或者 Gradle 项目中添加 Swagger 相关的依赖。例如,如果你使用 Maven,可以在 `pom.xml` 文件中加入:
```xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.x.x</version> <!-- 根据实际版本更新 -->
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.x.x</version>
</dependency>
```
2. 配置 Springfox:在 Spring Boot 应用中,需要启用 Swagger 的支持。在主配置类上添加 `@EnableSwagger2WebMvc` 注解,并设置扫描路径和标题等信息:
```java
@SpringBootApplication
@EnableSwagger2WebMvc
public class Application {
// ...
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档标题")
.description("API 描述")
.contact(new Contact("开发者", "https://www.example.com", "dev@example.com"))
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.version("v1")
.build();
}
```
3. 自动标注注解:为了方便Swagger识别并展示方法,需使用 `@ApiOperation`、`@ApiParam` 等注解来标记 API 和参数。
4. 部署UI:如果你想要访问 Swagger UI 页面,还需要配置一个静态资源处理器,如 WebMvcConfigurer 接口,以便暴露 Swagger 的 HTML 资源:
```java
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/swagger-ui/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
```
阅读全文
相关推荐


















