- Swagger Codegen: 通过Codegen
可以将描述文件生成html格式和cwiki形式的接口文档,同时也能生成多钟语言的服务端和客户端的代码。支持通过jar包,docker,node等方式在本地化执行生成。也可以在后面的Swagger
Editor中在线生成。
- Swagger
UI:提供了一个可视化的UI页面展示描述文件。接口的调用方、测试、项目经理等都可以在该页面中对相关接口进行查阅和做一些简单的接口请求。该项目支持在线导入描述文件和本地部署UI项目。
- Swagger Editor:
类似于markendown编辑器的编辑Swagger描述文件的编辑器,该编辑支持实时预览描述文件的更新效果。也提供了在线编辑器和本地部署编辑器两种方式。
- Swagger Inspector: 感觉和postman差不多,是一个可以对接口进行测试的在线版的postman。比在Swagger
UI里面做接口请求,会返回更多的信息,也会保存你请求的实际请求参数等数据。
- Swagger Hub:集成了上面所有项目的各个功能,你可以以项目和版本为单位,将你的描述文件上传到Swagger
Hub中。在Swagger Hub中可以完成上面项目的所有工作,需要注册账号,分免费版和收费版。
package com.programb.example;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import static org.springframework.boot.SpringApplication.run;
@ComponentScan(basePackages ="com.programb.example")
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext run = run(Application.class, args);
}
}
package com.programb.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.programb.example.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("更多请关注https://blog.csdn.net/programb")
.termsOfServiceUrl("https://blog.csdn.net/programb")
.contact("abel")
.version("1.0")
.build();
}
}
package com.programb.example.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name = "sec_user")
public class User {
@Id
@GeneratedValue
private Long id;
@Column(name = "name")
private String name;
@Column(name = "password")
private String password;
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
@Column(name = "mobilephone")
private String mobilephone;
@Column(name = "telephone")
private String telephone;
@Column(name = "user_type")
private Integer userType;
@Column(name = "create_by")
private String createBy;
@Column(name = "create_time")
private Date createTime;
@Column(name = "update_by")
private String updateBy;
@Column(name = "update_time")
private Date updateTime;
@Column(name = "disabled")
private Integer disabled;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDisabled() {
return disabled;
}
public void setDisabled(Integer disabled) {
this.disabled = disabled;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
package com.programb.example.config;
import java.beans.PropertyVetoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@Configuration
public class DBConfig {
@Autowired
private Environment env;
@Bean(name="dataSource")
public ComboPooledDataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("ms.db.driverClassName"));
dataSource.setJdbcUrl(env.getProperty("ms.db.url"));
dataSource.setUser(env.getProperty("ms.db.username"));
dataSource.setPassword(env.getProperty("ms.db.password"));
dataSource.setMaxPoolSize(20);
dataSource.setMinPoolSize(5);
dataSource.setInitialPoolSize(10);
dataSource.setMaxIdleTime(300);
dataSource.setAcquireIncrement(5);
dataSource.setIdleConnectionTestPeriod(60);
return dataSource;
}
}
package com.programb.example.config;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories("com.programb.example.dao")
@EnableTransactionManagement
@ComponentScan
public class JpaConfig {
@Autowired
private DataSource dataSource;
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.programb.example.bean");
factory.setDataSource(dataSource);
Map<String, Object> jpaProperties = new HashMap<String, Object>();
jpaProperties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy");
jpaProperties.put("hibernate.jdbc.batch_size",50);
factory.setJpaPropertyMap(jpaProperties);
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}
package com.programb.example.controller;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import io.swagger.annotations.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.programb.example.bean.User;
import com.programb.example.service.UserService;
import com.programb.example.util.CommonUtil;
@Controller
@RequestMapping(value = "/users")
@Api(value = "用户的增删改查")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "获取用户列表,目前没有分页")
public ResponseEntity<Object> findAll() {
return new ResponseEntity<>(userService.listUsers(), HttpStatus.OK);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "通过id获取用户信息", notes="返回用户信息")
public ResponseEntity<Object> getUserById(@PathVariable Integer id) {
return new ResponseEntity<>(userService.getUserById(Long.valueOf(id)), HttpStatus.OK);
}
@RequestMapping(value = "/byname", method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParam(paramType = "query",name= "username" ,value = "用户名",dataType = "string")
@ApiOperation(value = "通过用户名获取用户信息", notes="返回用户信息")
public ResponseEntity<Object> getUserByUserName(HttpServletRequest request) {
Map<String, Object> map = CommonUtil.getParameterMap(request);
String username = (String) map.get("username");
return new ResponseEntity<>(userService.getUserByUserName(username), HttpStatus.OK);
}
@RequestMapping(value = "/byUserNameContain", method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParam(paramType = "query",name= "username" ,value = "用户名",dataType = "string")
@ApiOperation(value = "通过用户名模糊搜索用户信息", notes="返回用户信息")
public ResponseEntity<Object> getUsers(HttpServletRequest request) {
Map<String, Object> map = CommonUtil.getParameterMap(request);
String username = (String) map.get("username");
return new ResponseEntity<>(userService.getByUsernameContaining(username), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
@ApiModelProperty(value="user",notes = "用户信息的json串")
@ApiOperation(value = "新增用户", notes="返回新增的用户信息")
public ResponseEntity<Object> saveUser(@RequestBody User user) {
return new ResponseEntity<>(userService.saveUser(user), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
@ApiModelProperty(value="user",notes = "修改后用户信息的json串")
@ApiOperation(value = "新增用户", notes="返回新增的用户信息")
public ResponseEntity<Object> updateUser(@RequestBody User user) {
return new ResponseEntity<>(userService.updateUser(user), HttpStatus.OK);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
@ApiOperation(value = "通过id删除用户信息", notes="返回删除状态1 成功 0 失败")
public ResponseEntity<Object> deleteUser(@PathVariable Integer id) {
return new ResponseEntity<>(userService.removeUser(id.longValue()), HttpStatus.OK);
}
}
package com.programb.example.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.programb.example.bean.User;
import java.util.List;
public interface UserJpaDao extends JpaRepository<User, Long> {
User findByName(String name);
User getOne(Long id);
List<User> findByUsernameContaining(String username);
User getByUsernameIs(String username);
@Query("select s from User s where name like CONCAT('%',:name,'%')")
List<User> findByNameLike(@Param("name") String name);
}
package com.programb.example.service;
import java.util.List;
import com.programb.example.bean.User;
public interface UserService {
public User getUserByUserName(String username);
public List<User> getByUsernameContaining(String username);
User saveUser(User user);
int removeUser(Long id);
User updateUser(User user);
User getUserById(Long id);
List<User> listUsers();
}
package com.programb.example.serviceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.programb.example.bean.User;
import com.programb.example.dao.UserJpaDao;
import com.programb.example.service.UserService;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserJpaDao userJpaDao;
@Override
public User getUserByUserName(String username) {
return userJpaDao.getByUsernameIs(username);
}
@Override
public List<User> getByUsernameContaining(String username) {
return userJpaDao.findByUsernameContaining(username);
}
@Override
public User saveUser(User user) {
return userJpaDao.save(user);
}
@Override
public int removeUser(Long id) {
try {
userJpaDao.delete(id);
}catch (Exception e) {
return 0;
}
return 1;
}
@Override
public User updateUser(User user) {
return userJpaDao.save(user);
}
@Override
public User getUserById(Long id) {
return userJpaDao.findOne(id);
}
@Override
public List<User> listUsers() {
return userJpaDao.findAll();
}
}
package com.programb.example.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
public class CommonUtil {
public static Map<String, Object> getParameterMap(HttpServletRequest request) {
Map<String, String[]> properties = request.getParameterMap();
Map<String, Object> returnMap = new HashMap<String, Object>();
Set<String> keySet = properties.keySet();
for(String key: keySet){
String[] values = properties.get(key);
String value = "";
if(values != null && (values.length==1&&StringUtils.isNotBlank(values[0]))?true:false){
for(int i=0;i<values.length;i++){
if(values[i] != null && !"".equals(values[i])){
value += values[i] + ",";
}
}
if(value != null && !"".equals(value)){
value = value.substring(0, value.length()-1);
}
if(key.equals("keywords")){
value = value.replace("_", "\\_").replace("%", "\\%");
}
returnMap.put(key, value);
}
}
return returnMap;
}
}
server.port=8099
ms.db.driverClassName=com.mysql.jdbc.Driver
ms.db.url=jdbc:mysql://localhost:3306/abeldb?sprepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&characterEncoding=utf-8&allowMultiQueries=true
ms.db.username=root
ms.db.password=admin
ms.db.maxActive=500
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.programb</groupId>
<artifactId>springboot-swagger-ui</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<properties>
<start-class>com.programb.Application</start-class>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<!-- springboot -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--db-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--util-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
</project>