前几天接触一个项目,里面原本是有swagger的,不过是重写的页面,而且里面的接口测试api,都是写死的,无奈,于是自己去找个轮子,集成了一下新的swagger;

首先:

pom.xml里添加依赖:

        <!-- swagger -->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.6.0.RELEASE</version>
        </dependency>

这里使用的是码云上大佬集成好的swagger,下面是链接地址:

spring-boot-starter-swagger

接下来,在配置文件.yml中添加相对的配置:

# 配置swagger
swagger:
    enabled: true
    base-package: com.a.b
    base-path: /**
    title: abc
    version: 1.0.0.SNAPSHOT
    description: 管理后端服务
    contact:
        name: a

这里的title可以是项目名称;base-package是扫描的包路径;base-path是url路径

配置好了以后,接下来,我觉得这一步是比较重要的:

添加对应的配置类:

package com.wxy.cloud.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 配置对应的路径
 */
@Configuration
public class ServletContextConfig extends WebMvcConfigurationSupport {

	/**
	 *  配置路径
	 * 
	 * @param registry
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**").addResourceLocations("classpath:/static/").addResourceLocations("classpath:/views/");
		registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		super.addResourceHandlers(registry);
	}


}

这里OK以后,就是在启动类上添加如下注解:

@EnableSwagger2Doc

 

接下来启动项目,如果你的项目端口号是8080的话;

进入localhost:8080:swagger-ui.html

完美;

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐