要在Spring MVC项目中配置Swagger,你需要以下步骤:

  1. 添加Swagger依赖到你的

pom.xml文件中。

  1. 配置Swagger的Java配置类。
  2. 创建Swagger的配置文件。
  3. 在Spring MVC的控制器中添加Swagger注解。

以下是一个简化的例子:

Step 1: 添加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>

Step 2: 创建Swagger配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
import java.util.Collections;
 
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @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 ApiInfo(
                "My API Title",
                "My API Description",
                "1.0",
                "urn:tos",
                Default.DEFAULT_CONTACT,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                Collections.emptyList());
    }
}

Step 3: 在Spring MVC的控制器中添加Swagger注解

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 = "My Controller API", description = "My Controller Description")
public class MyController {
 
    @GetMapping("/hello")
    @ApiOperation(value = "Says hello", response = String.class)
    public String hello() {
        return "Hello, Swagger!";
    }
}

Step 4: 确保你的Spring MVC应用程序的启动类或配置中包含了Swagger配置类。

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@ComponentScan(basePackages = "com.yourpackage") // 指定扫描的包路径
public class AppConfig {
}

完成这些步骤后,你可以启动你的Spring MVC应用程序,并通过访问 http://:/context-path/swagger-ui.html 来查看Swagger文档界面。