在 CentOS 系統中,要自定義 Swagger 注解,你需要遵循以下步驟:
首先,確保你的項目中包含了 Swagger 和相關依賴。在 Maven 項目的 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>
在項目中創建一個新的 Java 類,用于定義你的自定義注解。例如,創建一個名為 MyCustomAnnotation.java
的文件:
package com.example.demo.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
String value() default "";
}
在這個例子中,我們創建了一個名為 MyCustomAnnotation
的注解,它可以應用于方法和類,并在運行時保留。
在你的項目中使用自定義注解。例如,在一個名為 MyController.java
的控制器類中:
package com.example.demo.controller;
import com.example.demo.annotation.MyCustomAnnotation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@MyCustomAnnotation("This is a custom annotation example")
public class MyController {
@GetMapping("/hello")
@MyCustomAnnotation("This is a custom annotation for the hello method")
public String hello() {
return "Hello, World!";
}
}
在這個例子中,我們將 MyCustomAnnotation
注解應用于控制器類和方法。
為了讓 Swagger 識別你的自定義注解,你需要配置 Swagger。創建一個名為 SwaggerConfig.java
的文件:
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
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.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My API")
.description("My API description")
.version("1.0.0")
.build();
}
}
在這個例子中,我們配置了一個名為 api
的 Docket Bean,它將掃描 com.example.demo.controller
包中的所有控制器,并為它們生成 API 文檔。
啟動你的應用程序,然后訪問 Swagger UI 頁面(通常是 http://localhost:8080/swagger-ui.html
)。你應該能看到你的自定義注解出現在 API 文檔中。
以上步驟應該可以幫助你在 CentOS 系統中自定義 Swagger 注解。根據你的需求,你可以進一步擴展和自定義注解。