SpringBoot2.0项目模块整合之Swagger2(自定UI,服务启动加载,拦截器),静态资源的访问

本文介绍如何在Spring Boot项目中集成Swagger,实现API文档的自动生成及接口测试功能。包括依赖配置、模型注解、控制器注解及配置类的详细设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

swagger是一款高效易用的嵌入式文档插件,同时支持在线测试接口,快速生成客户端代码。spring-boot-starter-swagger通过spring-boot方式配置的swagger实现。完美并且完整的支持swagger-spring的所有配置项,配置及其简单,容易上手。支持api分组配置,通过正则表达式方式分组。支持分环境配置,你可以很容易让你的项目api文档在开发环境,测试环境。

依赖包

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.7.0</version>
		</dependency>

 

model中常用的注解:@ApiModel 注解类名,@ApiModelProperty 注解方法或者参数名

UserModel

package com.swagger.model;

import java.io.Serializable;

import io.swagger.annotations.ApiModelProperty;

/**
 * <p>
 * 角色
 * </p>
 * 
 * @author lixin(1309244704@qq.com)
 * @since 2018-08-03
 */
public class UserModel implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@ApiModelProperty(value = "id", required = false, position = 1, example = "10001")
	private Long userId;
	
	@ApiModelProperty(value = "编号", required = false, position = 1, example = "10001")
	private String userCode;
	
	@ApiModelProperty(value = "名称", required = false, position = 1, example = "张三")
	private String userName;
	
	public UserModel() {
		
	}
	
	public UserModel(long userId, String userCode,String userName) {
		this.setUserId(userId);
		this.setUserCode(userCode);
		this.setUserName(userName);
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public String getUserCode() {
		return userCode;
	}

	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	@Override
	public String toString() {
		return "UserModel [userId=" + userId + ", userCode=" + userCode + ", userName=" + userName + "]";
	}

}

控制器中常用的注解: @Api 注解控制器显示的标识,有tags和description可以配置控制器显示的标识;@ApiOperation 用来注解控制器方法显示的标识; @ApiParam 用来注解控制器方法参数的名字,控制器方法在文档中需要显示的默认值

UserController

package com.swagger.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.swagger.api.IUserService;
import com.swagger.model.UserModel;
import com.swagger.util.ApiConst;
import com.swagger.util.ResultEntity;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * <p>
 * 角色前端控制器
 * </p>
 *
 * @author lixin(1309244704@qq.com)
 * @since 2018-08-03
 */
@Controller
@RequestMapping("/user")
public class UserController {

	private @Autowired IUserService userService;

	@ApiOperation(value = "添加")
	@RequestMapping(value = "/addUser", method = RequestMethod.POST, produces = {
			MediaType.APPLICATION_JSON_UTF8_VALUE })
	public @ResponseBody ResultEntity<String> addUser(
			@ApiParam(value = "id", required = true) @RequestParam(value = "userId", required = true) Long userId,
			@ApiParam(value = "角色编号", required = true) @RequestParam(value = "userCode", required = true) String userCode,
			@ApiParam(value = "角色名称", required = true) @RequestParam(value = "userName", required = true) String userName) {
		try {
			UserModel user = new UserModel();
			user.setUserId(userId);
			user.setUserCode(userCode);
			user.setUserName(userName);
			userService.addUser(user);
			return new ResultEntity<String>(ApiConst.CODE_SUCC, ApiConst.DESC_SUCC);
		} catch (Exception e) {
			e.getStackTrace();
		}
		return new ResultEntity<String>(ApiConst.CODE_FAIL, ApiConst.DESC_FAIL);
	}
	@ApiOperation(value = "查询")
	@RequestMapping(value = "/getUser", method = RequestMethod.POST, produces = {
			MediaType.APPLICATION_JSON_UTF8_VALUE })
	public @ResponseBody ResultEntity<List<UserModel>> getUser() {
		try {
			List<UserModel> list = userService.getUser();
			return new ResultEntity<List<UserModel>>(ApiConst.CODE_SUCC, ApiConst.DESC_SUCC,list);
		} catch (Exception e) {
			e.getStackTrace();
		}
		return new ResultEntity<List<UserModel>>(ApiConst.CODE_FAIL, ApiConst.DESC_FAIL);
	}
	
}

swaggerConfig配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Bean
	public Docket customDocket() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.basePackage("com.swagger.web.controller"))
				.paths(PathSelectors.any())
				.build();
	}

	private ApiInfo apiInfo() {
		 return new ApiInfoBuilder()
//	                .title("")
	                .description("测试接口Api")
	                .termsOfServiceUrl("127.0.0.1")
	                .version("1.0")
	                .build();
	}

然后我们在看看我们自己的Ui,虽然和v2版的差不多,但是里面有些不同

这是我们Ui的静态资源

实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。 
为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。

SwaggerCommandLineRunner

package com.swagger.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/** 
* @ClassName: SwaggerCommandLineRunner 
* @Description: TODO(启动加载swagger) 
* @author lixin
* @date 2018年8月17日 下午4:17:32 
*  
*/
@Component
@Order(value = 1)
public class SwaggerCommandLineRunner implements CommandLineRunner {

	private static Logger logger = LoggerFactory.getLogger(SwaggerCommandLineRunner.class);

	@Override
	public void run(String... args) throws Exception {
		logger.debug(">>>>>>>>>>>>>>服务启动加载:swagger初始化<<<<<<<<<<<<<");
	}

}


OK,下面来说一说SpringBoot 的拦截器配置,这里的拦截器配置分为  SpringBoot 1.X版本和 SpringBoot 2.X版本:

SpringBoot 1.X用的是 继承 WebMvcConfigurerAdapter类;

在SpringBoot 2.X中,WebMvcConfigurerAdapter这个类已经过时了,可以用继承WebMvcConfigurationSupport,也可以实现 WebMvcConfigurer这个接口;在使用这个SpringBoot 2.X配置拦截器后,发现静态资源居然也被拦截了,这里就需要我们在过滤条件时,放开静态资源路径,我使用的是实现 WebMvcConfigurer这个接口。下面是拦截器的配置:

WebInterceptor

package com.swagger.config;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONObject;

/**  
* @ClassName: WebInterceptor  
* @Description: TODO()  
* @author lixin(1309244704@qq.com)  
* @date 2018年8月18日 下午2:58:42  
* @version V1.0  
*/ 
public class WebInterceptor implements HandlerInterceptor {
	
	 @Override
	    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
		 System.out.println("==============  request before  ==============");
	        httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
	        httpServletResponse.addHeader("Access-Control-Allow-Methods", "*");
	        httpServletResponse.addHeader("Access-Control-Max-Age", "1800");
	        httpServletResponse.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");
	        httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
	        httpServletResponse.setContentType("application/json;charset=UTF-8");
	        httpServletResponse.setHeader("Cache-Control", "no-cache");
	        String token = httpServletRequest.getHeader("token");
			if(null != token){
				return true;
			}
			PrintWriter out = httpServletResponse.getWriter();
			JSONObject res = new JSONObject();
		    res.put("success","false");
		    res.put("msg","登录信息失效,请重新登录!");
		    out.append(res.toString());
			out.flush();  
			return false;
	    }

	    @Override
	    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
	        System.out.println("==============  request  ==============");
	    }

	    @Override
	    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
	        System.out.println("==============  request completion  ==============");
	    }
}

WebMvcConfig

package com.swagger.config;

import java.util.Arrays;

import javax.servlet.MultipartConfigElement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**  
* @ClassName: WebMvcConfig  
* @Description: TODO()  
* @author lixin(1309244704@qq.com)  
* @date 2018年8月18日 下午2:58:52  
* @version V1.0  
*/ 
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
	
	private static Logger logger = LoggerFactory.getLogger(SwaggerCommandLineRunner.class);

	/* (非 Javadoc)
	* <p>Title: addCorsMappings</p>
	* <p>Description: 跨域</p>
	* @param registry
	* @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#addCorsMappings(org.springframework.web.servlet.config.annotation.CorsRegistry)
	*/
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
			.allowedOrigins("*")
			.allowCredentials(true)
			.allowedMethods("GET", "POST", "DELETE", "PUT")
			.maxAge(3600);
	}
	
	 public void addInterceptors(InterceptorRegistry registry) {
//		 	registry.addInterceptor(new WebInterceptor());
	        registry.addInterceptor(new WebInterceptor()).excludePathPatterns(Arrays.asList("/static/**","/api/**")); //放开静态资源拦截
	        logger.debug(">>>>>>>>>>>>>> 拦截器注册完毕<<<<<<<<<<<<<");
	    }
	 /** 上传附件容量限制 */
		@Bean
		public MultipartConfigElement multipartConfigElement() {
			MultipartConfigFactory factory = new MultipartConfigFactory();
			factory.setMaxFileSize("102400KB");
			factory.setMaxRequestSize("112400KB");
			return factory.createMultipartConfig();
		}
}

OK到这里,我们的配置也就结束了。

参考文档:https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/

Github下载路径:测试项目demo

访问的路径是:http://localhost:8001/api/index.html,下面是我做测试的图

不填token

填入token

<think>嗯,用户想了解在Spring Boot 2.2.2.RELEASE中集成Swagger-Bootstrap-UI的教程。首先,我需要回忆一下SwaggerSwagger-Bootstrap-UI的基本概念。Swagger是用来生成API文档的工具,而Swagger-Bootstrap-UI是它的一个美化版本,界面更友好。 接下来,用户提到的Spring Boot版本是2.2.2.RELEASE,这个版本可能对依赖库有特定要求。我需要确认SwaggerSwagger-Bootstrap-UI在这个Spring Boot版本中的兼容性。通常,Springfox Swagger2Swagger UI的版本需要匹配,可能使用2.9.2或者更高版本。 然后,步骤方面,应该包括添加Maven依赖、配置Swagger、初始化配置类,以及如何访问生成的文档。可能需要参考用户提供的引用内容中的配置类,比如使用@Configuration注解的类,以及如何定义Docket bean。 另外,用户提供的引用中有User实体类,可能需要考虑在API文档中如何展示实体类,可能需要添加@ApiModel注解之类的。不过用户的问题主要集中在集成过程,所以可能不需要深入实体类的部分。 需要注意的点:是否正确引入了Swagger-Bootstrap-UI的依赖,是否需要在配置类中启用Swagger,以及可能的版本冲突问题。比如,Spring Boot 2.2.2可能使用较新的Spring框架版本,需要确保Swagger相关库与之兼容。 还有,生成的文档访问路径是什么,是否需要额外的安全配置,比如在Spring Security中放行相关路径。但用户的问题中没有提到安全框架,可能暂时不需要涉及。 最后,验证步骤是否完整,比如启动应用后访问/doc.html是否能正常看到美化后的界面。可能还需要测试一些API接口是否被正确收录和展示。</think>### Spring Boot 2.2.2.RELEASE集成Swagger-Bootstrap-UI教程 #### 1. 添加依赖 在`pom.xml`中引入以下依赖: ```xml <!-- Springfox Swagger2核心库 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- Swagger-Bootstrap-UI美化包 --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency> ``` #### 2. 创建Swagger配置类 ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 修改为你的控制器包路径 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文档") .description("Spring Boot 2.2.2集成Swagger-Bootstrap-UI示例") .version("1.0") .build(); } } ``` *注:配置类需使用@Configuration注解标识[^1]* #### 3. 实体类配置(可选) 若需展示实体类文档,可在User类添加注解: ```java @ApiModel("用户实体") @Getter @Setter @ToString public class User implements Serializable { @ApiModelProperty("登录名") private String loginName; @ApiModelProperty("密码") private String password; } ``` *参考用户实体类结构[^2]* #### 4. 访问文档 启动应用后访问: - 原生UI:`http://localhost:8080/swagger-ui.html` - 美化UI:`http://localhost:8080/doc.html` #### 5. 常见问题处理 1. **版本兼容性**:确保Spring Boot与Swagger版本匹配 2. **路径扫描**:检查`basePackage`配置是否正确 3. **静态资源拦截**:若使用MVC拦截器需排除`/v2/api-docs`和`/doc.html`路径
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值