一、导入依赖,引入swagger相关的jar:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
二、配置swagger:
@EnableWebMvc
@Configuration
public class SwaggerConfig {
private static final String VERSION = "1.0.0";
@Bean
public Docket createRestApi() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("默认项目名称") //网站标题
.description("项目名称swagger RESTFUL APIs......") //网站描述
.version(VERSION) //版本
.contact(new Contact("张先生博客", "https://www.zhangfayuan.cn/", "xxx@163.com")) //联系人
.license("The Apache License") //协议
.licenseUrl("http://www.baidu.com") //协议url
.build();
return new Docket(DocumentationType.SWAGGER_2) //swagger版本
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.jeffrey.basis_build.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo);
}
}
三、运行项目,访问 http://localhost:port/swagger-ui/index.html,Swagger安装完成。
四、导入依赖 swagger-bootstrap-ui:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
五、配置 swagger-bootstrap-ui:
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOriginPatterns("*").allowedHeaders("*").allowCredentials(true).allowedMethods("*");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
六、重启项目,访问 http://localhost:port/doc.html,大功告成。