DBILITY

spring boot RESTful + swagger2 sample 본문

java/spring cloud

spring boot RESTful + swagger2 sample

DBILITY 2019. 9. 4. 10:47
반응형

이 예제는 spring boot를 이용해 Restful API를 작성하며, API 문서화는 swagger를 사용한다.
swagger는 Restful API를 설계,빌드,문서화하는 도구로 문서화를 위해 소스코드에서 swagger 파일을 생성해 본다.
swagger-ui를 통해 문서를 확인하고, API별로 테스트도 가능하다.
lombok plugin을 통해 model class를 생성하며 ide는 sts4를 사용했다.

gradle과 yaml을 많이 사용한다는데 나는 maven과 properties가 아직 익숙하니 그대로 사용하였다.

  1. pom.xml
    pom.xml
    다운로드

    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>2.1.8.RELEASE</version>
    		<relativePath/> <!-- lookup parent from repository -->
    	</parent>
    	<groupId>com.dbility.cloud</groupId>
    	<artifactId>spring-restful</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>spring-restful</name>
    	<description>Demo project for Spring Boot</description>
    
    	<properties>
    		<java.version>1.8</java.version>
    		<swagger.version>2.9.2</swagger.version>
    		<maven-model.version>3.6.1</maven-model.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-devtools</artifactId>
    			<scope>runtime</scope>
    			<optional>true</optional>
    		</dependency>
    		<dependency>
    			<groupId>org.projectlombok</groupId>
    			<artifactId>lombok</artifactId>
    			<optional>true</optional>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>io.springfox</groupId>
    			<artifactId>springfox-swagger2</artifactId>
    			<version>${swagger.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>io.springfox</groupId>
    			<artifactId>springfox-swagger-ui</artifactId>
    			<version>${swagger.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.maven</groupId>
    			<artifactId>maven-model</artifactId>
    			<version>${maven-model.version}</version>
    		</dependency>
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    
    </project>
  2. application.properties
    server.port=8880
    
    logging.level.root=off
    logging.level.org.springframework=info
    logging.level.com.dbility=debug
  3. main Application Swagger 활성화
    package com.dbility.cloud.spring;
    
    import java.io.FileReader;
    import java.io.IOException;
    
    import org.apache.maven.model.Model;
    import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
    import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    
    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;
    
    @EnableSwagger2
    @SpringBootApplication
    public class SpringRestfulApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(SpringRestfulApplication.class, args);
    	}
    
    	@Bean
    	public Docket api() throws IOException, XmlPullParserException {
    
    		MavenXpp3Reader reader = new MavenXpp3Reader();
    		Model model = reader.read(new FileReader("pom.xml"));
    
    		return new Docket(DocumentationType.SWAGGER_2)
    				.select()
    				.apis(RequestHandlerSelectors.basePackage("com.dbility"))
    				.paths(PathSelectors.any())
    				.build()
    				.apiInfo(apiInfo(model.getVersion()));
    	}
    
    	private ApiInfo apiInfo(String version) {
    		ApiInfoBuilder builder = new ApiInfoBuilder();
    		builder.title("Spring-Restful example")
    				.description("Spring-Restfull First Example")
    				.contact(new Contact("hyperrookie", "http://www.dbility.com", "hyperrookie@gmail.com"))
    				.version(version);
    
    		return builder.build();
    	}
    
    }
  4. Emp model class
    package com.dbility.cloud.spring.model;
    
    import java.util.Date;
    
    import lombok.Data;
    
    @Data
    public class Emp {
    
    	private Long empno;
    	private String ename;
    	private String job;
    	private Long mgr;
    	private Date hiredate;
    	private double sal;
    	private Long deptno;
    }
  5. EmpController class
    package com.dbility.cloud.spring.controller;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.dbility.cloud.spring.model.Emp;
    
    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    @RestController
    @RequestMapping(value = "/emp")
    public class EmpController {
    
    	private List<Emp> emps = new ArrayList<Emp>();
    
    	@GetMapping
    	public List<Emp> findAll() throws Exception {
    		log.debug("GET ALL --> {}", emps);
    		return emps;
    	}
    
    	@GetMapping(value = "/{id}")
    	public Emp findById(@RequestParam Longid) throws Exception {
    		log.debug("GET param --> {}", id);
    		Emp emp = emps.stream().filter(x -> x.getEmpno().equals(id)).findFirst().get();
    		log.debug("GET result--> {}", emp);
    		return emp;
    	}
    
    	@PostMapping
    	public Emp add(@RequestBody Emp emp) throws Exception {
    		emp.setEmpno((long) (emps.size() + 1));
    		emps.add(emp);
    		log.debug("POST --> {}", emp);
    
    		return emp;
    	}
    
    	@DeleteMapping
    	public void delete(@RequestParam("id") Long id) throws Exception {
    		List<Emp> es = emps.stream().filter(x -> x.getEmpno().equals(id)).collect(Collectors.toList());
    		emps.removeAll(es);
    		log.debug("DELETE --> {}", es);
    	}
    
    	@PutMapping
    	public void update(@RequestBody Emp emp) throws Exception {
    		Emp e = emps.stream().filter(x -> x.getEmpno().equals(emp.getEmpno())).findFirst().get();
    		emps.set(emps.indexOf(e), emp);
    		log.debug("PUT --> {}", emp);
    	}
    
    }
  6. swagger-ui

 

 

반응형
Comments