在CentOS系統中,如果你想要為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>
請注意,版本號可能會隨著時間的推移而更新,所以請確保使用最新的穩定版本。
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 CustomSwaggerAnnotation {
String value() default "";
}
這個CustomSwaggerAnnotation
注解可以用于方法或類,并且它有一個名為value
的默認屬性。
@RestController
@RequestMapping("/api")
public class MyController {
@CustomSwaggerAnnotation("這是一個自定義注解的示例")
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
SwaggerConfig.java
: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();
}
}
ModelConverter
來處理這個注解。這通常涉及到一些高級配置,可能需要深入了解Swagger的內部工作原理。請注意,Swagger 3(Springfox 3.0.0及以上版本)引入了對自定義注解的原生支持,這可能會簡化上述過程。如果你使用的是Swagger 3,你可以直接在注解中使用@ApiModelProperty
或其他相關注解,并通過配置類來處理這些注解。
以上步驟提供了一個基本的框架,但具體實現可能需要根據你的項目需求和Swagger版本進行調整。