springboot项目引入swagger
    		       		warning:
    		            这篇文章距离上次修改已过424天,其中的内容可能已经有所变动。
    		        
        		                
                要在Spring Boot项目中引入Swagger,你需要按照以下步骤操作:
- 添加Swagger依赖到你的
pom.xml文件中。 - 配置Swagger。
 - 创建Swagger配置类。
 - 使用Swagger注解。
 
以下是具体的实现步骤和示例代码:
- 添加Swagger依赖到
pom.xml: 
<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>- 配置Swagger,创建一个配置类如
SwaggerConfig.java: 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}- 在你的Controller类或方法上使用Swagger注解来描述API:
 
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@Api(value = "示例控制器", description = "描述信息")
public class ExampleController {
 
    @GetMapping("/example")
    @ApiOperation(value = "获取示例数据", notes = "更详细的描述信息")
    public String getExample() {
        return "Hello, Swagger!";
    }
}完成以上步骤后,你可以启动Spring Boot应用,并通过访问http://<host>:<port>/swagger-ui.html来查看Swagger生成的API文档。
评论已关闭