# 示例程序
【pom.xml】
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
【application.properties】
server.port=8080
spring.application.name=mySwagger
management.server.port=8080
management.endpoints.web.exposure.include=*
【SwaggerConfig.java】
package com.chz.mySwagger.config;
@Configuration
public class SwaggerConfig {
@Autowired
private TypeResolver typeResolver;
@Bean
public Docket petApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(
newRule(
typeResolver.resolve(
DeferredResult.class, typeResolver.resolve(ResponseEntity.class, WildcardType.class)
),
typeResolver.resolve(WildcardType.class)
)
)
.useDefaultResponseMessages(false)
.globalResponses(HttpMethod.GET,
singletonList(new ResponseBuilder()
.code("500")
.description("500 message")
.representation(MediaType.TEXT_XML)
.apply(r ->
r.model(m ->
m.referenceModel(ref ->
ref.key(k ->
k.qualifiedModelName(q ->
q.namespace("some:namespace").name("ERROR")
)
)
)
)
)
.build()))
.securitySchemes(singletonList(apiKey()))
.securityContexts(singletonList(securityContext()))
.enableUrlTemplating(true)
.globalRequestParameters(
singletonList(
new springfox.documentation.builders.RequestParameterBuilder()
.name("someGlobalParameter")
.description("Description of someGlobalParameter")
.in(ParameterType.QUERY)
.required(true)
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.build()
)
)
.tags(new Tag("Pet Service", "All apis relating to pets"));
}
private ApiKey apiKey() {
return new ApiKey("mykey", "api_key", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/anyPath.*"))
.build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return singletonList(new SecurityReference("mykey", authorizationScopes));
}
@Bean
SecurityConfiguration security() {
return SecurityConfigurationBuilder.builder()
.clientId("test-app-client-id")
.clientSecret("test-app-client-secret")
.realm("test-app-realm")
.appName("test-app")
.scopeSeparator(",")
.additionalQueryStringParams(null)
.useBasicAuthenticationWithAccessCodeGrant(false)
.enableCsrfSupport(false)
.build();
}
@Bean
UiConfiguration uiConfig() {
return UiConfigurationBuilder.builder()
.deepLinking(true)
.displayOperationId(false)
.defaultModelsExpandDepth(1)
.defaultModelExpandDepth(1)
.defaultModelRendering(ModelRendering.EXAMPLE)
.displayRequestDuration(false)
.docExpansion(DocExpansion.NONE)
.filter(false)
.maxDisplayedTags(null)
.operationsSorter(OperationsSorter.ALPHA)
.showExtensions(false)
.showCommonExtensions(false)
.tagsSorter(TagsSorter.ALPHA)
.supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
.validatorUrl(null)
.build();
}
}
【Test1Controller.java】
package com.chz.mySwagger.controller1;
@Api(tags="chz-Test1Controller")
@Slf4j
@RestController
@RequestMapping("/test1")
public class Test1Controller {
@ApiOperation(value="第一个测试方法-value",notes="第一个测试方法-notes")
@ApiImplicitParams({
@ApiImplicitParam(name="p1",value="p1-value", defaultValue = "p1-defaultValue"),
@ApiImplicitParam(name="p2",value="p2-value", defaultValue = "p2-defaultValue")
})
@ApiResponses({
@ApiResponse(code = 200, message = "请求成功"),
})
@GetMapping("/test1")
public String test1(
@RequestParam(value = "p1")String p1,
@RequestParam(value = "p2")String p2
) {
return "test1: p1="+p1+", p2="+p2+";";
}
}
【Test2Controller.java】
package com.chz.mySwagger.controller2;
@Api(tags="chz-Test2Controller")
@Slf4j
@RestController
@RequestMapping("/test2")
public class Test2Controller {
@ApiOperation(value="第一个测试方法-value",notes="第一个测试方法-notes")
@ApiImplicitParams({
@ApiImplicitParam(name="p1",value="p1-value", defaultValue = "p1-defaultValue"),
@ApiImplicitParam(name="p2",value="p2-value", defaultValue = "p2-defaultValue")
})
@ApiResponses({
@ApiResponse(code = 200, message = "请求成功"),
})
@GetMapping("/test1")
public String test1(
@RequestParam(value = "p1")String p1,
@RequestParam(value = "p2")String p2
) {
return "test1: p1="+p1+", p2="+p2+";";
}
}
【IndexController.java】
package com.chz.mySwagger.controller1;
@Slf4j
@Controller
@RequestMapping("/")
public class IndexController {
@GetMapping("/")
public String index() {
return "redirect:/swagger-ui/index.html";
}
}
【MySwaggerTest.java】
package com.chz.mySwagger;
@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackageClasses = {
Test1Controller.class,
Test2Controller.class,
})
public class MySwaggerTest {
public static void main(String[] args) {
SpringApplication.run(MySwaggerTest.class, args);
}
}
启动【MySwaggerTest】,访问【http://localhost:8080/swagger-ui/index.html】
# 参考资料
https://springfox.github.io/springfox/docs/current/#introduction