Browse Source

add swagger2 examples

纯洁的微笑 6 years ago
parent
commit
832664240c

+ 58 - 0
spring-boot-swagger/pom.xml

@@ -0,0 +1,58 @@
+<?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>
+	<artifactId>spring-boot-swagger</artifactId>
+	<name>Spring Boot swagger Sample</name>
+	<description>Spring Boot swagger Sample</description>
+
+	<parent>
+		<groupId>org.springframework.boot</groupId>
+		<artifactId>spring-boot-starter-parent</artifactId>
+		<version>2.1.0.RELEASE</version>
+		<relativePath/> <!-- lookup parent from repository -->
+	</parent>
+
+	<dependencies>
+		<!-- Compile -->
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter-web</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>io.springfox</groupId>
+			<artifactId>springfox-swagger2</artifactId>
+			<version>2.9.2</version>
+		</dependency>
+		<dependency>
+			<groupId>io.springfox</groupId>
+			<artifactId>springfox-swagger-ui</artifactId>
+			<version>2.9.2</version>
+		</dependency>
+		<!-- Test -->
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter-test</artifactId>
+			<scope>test</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-devtools</artifactId>
+			<scope>runtime</scope>
+			<optional>true</optional>
+		</dependency>
+	</dependencies>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.springframework.boot</groupId>
+				<artifactId>spring-boot-maven-plugin</artifactId>
+				<configuration>
+					<fork>true</fork>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

+ 15 - 0
spring-boot-swagger/src/main/java/com/neo/SwaggerApplication.java

@@ -0,0 +1,15 @@
+
+package com.neo;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+
+@SpringBootApplication
+public class SwaggerApplication {
+
+	public static void main(String[] args) {
+		SpringApplication.run(SwaggerApplication.class, args);
+	}
+
+}

+ 112 - 0
spring-boot-swagger/src/main/java/com/neo/config/BaseResult.java

@@ -0,0 +1,112 @@
+package com.neo.config;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+
+/**
+ * 通用响应对象
+ */
+@ApiModel(description = "响应对象")
+public class BaseResult<T> {
+    private static final int SUCCESS_CODE = 0;
+    private static final String SUCCESS_MESSAGE = "成功";
+
+    @ApiModelProperty(value = "响应码", name = "code", required = true, example = "" + SUCCESS_CODE)
+    private int code;
+
+    @ApiModelProperty(value = "响应消息", name = "msg", required = true, example = SUCCESS_MESSAGE)
+    private String msg;
+
+    @ApiModelProperty(value = "响应数据", name = "data")
+    private T data;
+
+    private BaseResult(int code, String msg, T data) {
+        this.code = code;
+        this.msg = msg;
+        this.data = data;
+    }
+
+    private BaseResult() {
+        this(SUCCESS_CODE, SUCCESS_MESSAGE);
+    }
+
+    private BaseResult(int code, String msg) {
+        this(code, msg, null);
+    }
+
+    private BaseResult(T data) {
+        this(SUCCESS_CODE, SUCCESS_MESSAGE, data);
+    }
+
+    public static <T> BaseResult<T> success() {
+        return new BaseResult<>();
+    }
+
+    public static <T> BaseResult<T> successWithData(T data) {
+        return new BaseResult<>(data);
+    }
+
+    public static <T> BaseResult<T> failWithCodeAndMsg(int code, String msg) {
+        return new BaseResult<>(code, msg, null);
+    }
+
+    public static <T> BaseResult<T> buildWithParam(ResponseParam param) {
+        return new BaseResult<>(param.getCode(), param.getMsg(), null);
+    }
+
+    public int getCode() {
+        return code;
+    }
+
+    public void setCode(int code) {
+        this.code = code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+
+    public T getData() {
+        return data;
+    }
+
+    public void setData(T data) {
+        this.data = data;
+    }
+
+
+
+    public static class ResponseParam {
+        private int code;
+        private String msg;
+
+        private ResponseParam(int code, String msg) {
+            this.code = code;
+            this.msg = msg;
+        }
+
+        public static ResponseParam buildParam(int code, String msg) {
+            return new ResponseParam(code, msg);
+        }
+
+        public int getCode() {
+            return code;
+        }
+
+        public void setCode(int code) {
+            this.code = code;
+        }
+
+        public String getMsg() {
+            return msg;
+        }
+
+        public void setMsg(String msg) {
+            this.msg = msg;
+        }
+    }
+}

+ 39 - 0
spring-boot-swagger/src/main/java/com/neo/config/SwaggerConfig.java

@@ -0,0 +1,39 @@
+package com.neo.config;
+
+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.service.Contact;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+@Configuration
+@EnableSwagger2
+public class SwaggerConfig {
+
+    @Bean
+    public Docket api() {
+        return new Docket(DocumentationType.SWAGGER_2)
+                .apiInfo(apiInfo())
+                .select()
+                // 自行修改为自己的包路径
+                .apis(RequestHandlerSelectors.basePackage("com.neo.controller"))
+                .paths(PathSelectors.any())
+                .build();
+    }
+
+    private ApiInfo apiInfo() {
+        return new ApiInfoBuilder()
+                .title("客户管理")
+                .description("客户管理中心 API 1.0 操作文档")
+                //服务条款网址
+                .termsOfServiceUrl("http://www.ityouknow.com/")
+                .version("1.0")
+                .contact(new Contact("纯洁的微笑", "http://www.ityouknow.com/", "ityouknow@126.com"))
+                .build();
+    }
+}

+ 85 - 0
spring-boot-swagger/src/main/java/com/neo/controller/MessageController.java

@@ -0,0 +1,85 @@
+
+package com.neo.controller;
+
+import com.neo.config.BaseResult;
+import com.neo.model.Message;
+import com.neo.repository.MessageRepository;
+import io.swagger.annotations.*;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+@Api(value = "消息", description = "消息操作 API", position = 100, protocols = "http")
+@RestController
+@RequestMapping("/")
+public class MessageController {
+
+	@Autowired
+	private  MessageRepository messageRepository;
+
+	@ApiOperation(
+			value = "消息列表",
+			notes = "完整的消息内容列表",
+			produces="application/json, application/xml",
+			consumes="application/json, application/xml",
+			response = List.class)
+	@GetMapping(value = "messages")
+	public List<Message> list() {
+		List<Message> messages = this.messageRepository.findAll();
+		return messages;
+	}
+
+	@ApiOperation(
+			value = "添加消息",
+			notes = "根据参数创建消息"
+	)
+	@ApiImplicitParams({
+			@ApiImplicitParam(name = "id", value = "消息 ID", required = true, dataType = "Long", paramType = "query"),
+			@ApiImplicitParam(name = "text", value = "正文", required = true, dataType = "String", paramType = "query"),
+			@ApiImplicitParam(name = "summary", value = "摘要", required = false, dataType = "String", paramType = "query"),
+	})
+	@PostMapping(value = "message")
+	public Message create(Message message) {
+		System.out.println("message===="+message.toString());
+		message = this.messageRepository.save(message);
+		return message;
+	}
+
+	@ApiOperation(
+			value = "修改消息",
+			notes = "根据参数修改消息"
+	)
+	@PutMapping(value = "message")
+	@ApiResponses({
+			@ApiResponse(code = 100, message = "请求参数有误"),
+			@ApiResponse(code = 101, message = "未授权"),
+			@ApiResponse(code = 103, message = "禁止访问"),
+			@ApiResponse(code = 104, message = "请求路径不存在"),
+			@ApiResponse(code = 200, message = "服务器内部错误")
+	})
+	public Message modify(Message message) {
+		Message messageResult=this.messageRepository.update(message);
+		return messageResult;
+	}
+
+	@PatchMapping(value="/message/text")
+	public BaseResult<Message> patch(Message message) {
+		Message messageResult=this.messageRepository.updateText(message);
+		return BaseResult.successWithData(messageResult);
+	}
+
+	@GetMapping(value = "message/{id}")
+	public Message get(@PathVariable Long id) {
+		Message message = this.messageRepository.findMessage(id);
+		return message;
+	}
+
+	@DeleteMapping(value = "message/{id}")
+	public void delete(@PathVariable("id") Long id) {
+		this.messageRepository.deleteMessage(id);
+	}
+
+
+
+}

+ 76 - 0
spring-boot-swagger/src/main/java/com/neo/controller/UserController.java

@@ -0,0 +1,76 @@
+package com.neo.controller;
+
+import com.neo.config.BaseResult;
+import com.neo.model.User;
+import io.swagger.annotations.*;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import springfox.documentation.annotations.ApiIgnore;
+
+import java.util.*;
+
+
+@Api(value = "用户管理", description = "用户管理API", position = 100, protocols = "http")
+@RestController
+@RequestMapping(value = "/user")
+public class UserController {
+    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());
+
+    @ApiOperation(value = "获取用户列表", notes = "查询用户列表")
+    @RequestMapping(value = {""}, method = RequestMethod.GET)
+    @ApiResponses({
+            @ApiResponse(code = 100, message = "异常数据")
+    })
+    public List<User> getUserList() {
+        return new ArrayList<>(users.values());
+    }
+
+    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "query"),
+            @ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "ipAddr", value = "ip哟", required = false, dataType = "String", paramType = "query")
+    })
+    @RequestMapping(value = "", method = RequestMethod.POST)
+    public BaseResult<User> postUser(@ApiIgnore User user) {
+        users.put(user.getId(), user);
+        return BaseResult.successWithData(user);
+    }
+
+    @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
+    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
+    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
+    public User getUser(@PathVariable Long id) {
+        return users.get(id);
+    }
+
+    @ApiOperation(value = "更新用户信息", notes = "根据用户ID更新信息")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "query"),
+            @ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String", paramType = "query")
+    })
+    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
+    public BaseResult<User> putUser(@PathVariable Long id, @ApiIgnore User user) {
+        User u = users.get(id);
+        u.setName(user.getName());
+        u.setAge(user.getAge());
+        users.put(id, u);
+        return BaseResult.successWithData(u);
+    }
+
+    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
+    public String deleteUser(@PathVariable Long id) {
+        users.remove(id);
+        return "success";
+    }
+
+    @RequestMapping(value = "/ignoreMe/{id}", method = RequestMethod.DELETE)
+    public String ignoreMe(@PathVariable Long id) {
+        users.remove(id);
+        return "success";
+    }
+}

+ 60 - 0
spring-boot-swagger/src/main/java/com/neo/model/Message.java

@@ -0,0 +1,60 @@
+package com.neo.model;
+
+import io.swagger.annotations.ApiModelProperty;
+
+import java.util.Calendar;
+import java.util.Date;
+
+import javax.validation.constraints.NotEmpty;
+
+
+public class Message {
+	private Long id;
+	@ApiModelProperty(value = "消息体")
+	private String text;
+	@ApiModelProperty(value = "消息总结")
+	private String summary;
+	private Date createDate;
+
+	public Long getId() {
+		return this.id;
+	}
+
+	public void setId(Long id) {
+		this.id = id;
+	}
+
+	public Date getCreateDate() {
+		return createDate;
+	}
+
+	public void setCreateDate(Date createDate) {
+		this.createDate = createDate;
+	}
+
+	public String getText() {
+		return this.text;
+	}
+
+	public void setText(String text) {
+		this.text = text;
+	}
+
+	public String getSummary() {
+		return this.summary;
+	}
+
+	public void setSummary(String summary) {
+		this.summary = summary;
+	}
+
+	@Override
+	public String toString() {
+		return "Message{" +
+				"id=" + id +
+				", text='" + text + '\'' +
+				", summary='" + summary + '\'' +
+				", createDate=" + createDate +
+				'}';
+	}
+}

+ 31 - 0
spring-boot-swagger/src/main/java/com/neo/model/User.java

@@ -0,0 +1,31 @@
+package com.neo.model;
+
+public class User {
+    private Long id;
+    private String name;
+    private int age;
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public int getAge() {
+        return age;
+    }
+
+    public void setAge(int age) {
+        this.age = age;
+    }
+}

+ 59 - 0
spring-boot-swagger/src/main/java/com/neo/repository/InMemoryMessageRepository.java

@@ -0,0 +1,59 @@
+package com.neo.repository;
+
+import com.neo.model.Message;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+@Service("messageRepository")
+public class InMemoryMessageRepository implements MessageRepository {
+
+	private static AtomicLong counter = new AtomicLong();
+	private final ConcurrentMap<Long, Message> messages = new ConcurrentHashMap<>();
+
+	@Override
+	public List<Message> findAll() {
+		List<Message> messages = new ArrayList<Message>(this.messages.values());
+		return messages;
+	}
+
+	@Override
+	public Message save(Message message) {
+		Long id = message.getId();
+		if (id == null) {
+			id = counter.incrementAndGet();
+			message.setId(id);
+		}
+		this.messages.put(id, message);
+		return message;
+	}
+
+	@Override
+	public Message update(Message message) {
+		this.messages.put(message.getId(), message);
+		return message;
+	}
+
+	@Override
+	public Message updateText(Message message) {
+		Message msg=this.messages.get(message.getId());
+		msg.setText(message.getText());
+		this.messages.put(msg.getId(), msg);
+		return msg;
+	}
+
+	@Override
+	public Message findMessage(Long id) {
+		return this.messages.get(id);
+	}
+
+	@Override
+	public void deleteMessage(Long id) {
+		this.messages.remove(id);
+	}
+
+}

+ 22 - 0
spring-boot-swagger/src/main/java/com/neo/repository/MessageRepository.java

@@ -0,0 +1,22 @@
+
+package com.neo.repository;
+
+import com.neo.model.Message;
+
+import java.util.List;
+
+public interface MessageRepository {
+
+	List<Message> findAll();
+
+	Message save(Message message);
+
+	Message update(Message message);
+
+	Message updateText(Message message);
+
+	Message findMessage(Long id);
+
+	void deleteMessage(Long id);
+
+}

+ 1 - 0
spring-boot-swagger/src/main/resources/application.properties

@@ -0,0 +1 @@
+logging.level.io.swagger.models.parameters.AbstractSerializableParameter=error

+ 8 - 0
spring-boot-swagger/src/main/resources/logback.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+
+	<include resource="org/springframework/boot/logging/logback/base.xml"/>
+
+	<!-- logger name="org.springframework" level="DEBUG"/-->
+
+</configuration>

+ 14 - 0
spring-boot-swagger/src/test/java/com/neo/SwaggerApplicationTests.java

@@ -0,0 +1,14 @@
+
+package com.neo;
+
+
+
+import org.junit.Test;
+
+public class SwaggerApplicationTests {
+
+	@Test
+	public void test() {
+	}
+
+}

+ 105 - 0
spring-boot-swagger/src/test/java/com/neo/web/MessageControllerTest.java

@@ -0,0 +1,105 @@
+package com.neo.web;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.context.WebApplicationContext;
+
+import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class MessageControllerTest {
+
+    @Autowired
+    private WebApplicationContext wac;
+
+    private MockMvc mockMvc;
+
+    @Before
+    public void setup() {
+        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
+        saveMessages();
+    }
+
+    @Test
+    public void saveMessage() throws Exception {
+        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
+        params.add("text", "text");
+        params.add("summary", "summary");
+        String mvcResult=  mockMvc.perform(MockMvcRequestBuilders.post("/message")
+                .params(params)).andReturn().getResponse().getContentAsString();
+        System.out.println("Result === "+mvcResult);
+    }
+
+    @Test
+    public void getAllMessages() throws Exception {
+        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.get("/messages"))
+                .andReturn().getResponse().getContentAsString();
+        System.out.println("Result === "+mvcResult);
+    }
+
+    @Test
+    public void getMessage() throws Exception {
+        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.get("/message/6"))
+                .andReturn().getResponse().getContentAsString();
+        System.out.println("Result === "+mvcResult);
+    }
+
+    @Test
+    public void modifyMessage() throws Exception {
+        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
+        params.add("id", "6");
+        params.add("text", "text");
+        params.add("summary", "summary");
+        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.put("/message").params(params))
+                .andReturn().getResponse().getContentAsString();
+        System.out.println("Result === "+mvcResult);
+    }
+
+    @Test
+    public void patchMessage() throws Exception {
+        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
+        params.add("id", "6");
+        params.add("text", "text");
+        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.patch("/message/text").params(params))
+                .andReturn().getResponse().getContentAsString();
+        System.out.println("Result === "+mvcResult);
+    }
+
+    @Test
+    public void deleteMessage() throws Exception {
+        mockMvc.perform(MockMvcRequestBuilders.delete("/message/6"))
+                .andReturn();
+        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.get("/messages"))
+                .andReturn().getResponse().getContentAsString();
+        System.out.println("Result === "+mvcResult);
+    }
+
+    private void  saveMessages()  {
+        for (int i=1;i<10;i++){
+            final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
+            params.add("id",""+i);
+            params.add("text", "text"+i);
+            params.add("summary", "summary"+i);
+            try {
+                MvcResult mvcResult=  mockMvc.perform(MockMvcRequestBuilders.post("/message")
+                        .params(params)).andReturn();
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+}