스프링 부트를 이용한 api서버를 만들겠습니다.
서버에 요청하면 json형식으로 결과를 내려주는 서버를 만들게 됩니다.
프로젝트 생성
메이븐 프로젝트를 생성해 줍니다.
new-project-Maven Project해서 생성하시던지
그냥 프로젝트 생성 후 confiture-convert to maven project를 해줍니다.
아래와 동일한 프로젝트 구조가 생성이 됩니다.
2016/09/07 - [개발/JAVA] - 스프링 부트(Spring boot)로 개발하기
라이브러리 추가
pom.xml
<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>net.donnert</groupId>
<artifactId>spring.boot.web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring.boot.web</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceencoding>UTF-8</project.build.sourceencoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
스프링 부트 parent와 starter-web을 달아줍니다.
배치때 사용한 것은 그냥 starter입니다. 뒤에 web을 붙여줍니다.
Application.java
package net.donnert.spring.boot.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
그냥 스타트.
Article.java
package net.donnert.spring.boot.web;
public class Article {
private long seq;
private String title;
private String text;
private String writer;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public long getSeq() {
return seq;
}
public void setSeq(long seq) {
this.seq = seq;
}
}
클라이언트로 전달 될 클래스입니다.
ArticleController.java
package net.donnert.spring.boot.web;
import java.util.ArrayList;
import java.util.List;
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;
@RestController
public class ArticleController {
@RequestMapping(value = "list", method = RequestMethod.GET)
public List test() {
List list = new ArrayList();
for(int i=1; i<=10; i++) {
Article article = new Article();
article.setSeq(i);
article.setText("This is text");
article.setTitle("This is title");
article.setWriter("I am writer");
list.add(article);
}
return list;
}
@RequestMapping(value = "article/{seq}", method = RequestMethod.GET)
public Article detail(@PathVariable("seq") long seq) {
Article article = new Article();
article.setSeq(seq);
article.setText("This is text");
article.setTitle("This is title");
article.setWriter("I am writer");
return article;
}
}
@RestController 어노테이션을 통해 컨트롤러를 restful로 정의해줍니다.
이렇게 될 경우 @ResponseBody가 필요 없어집니다.
목록과 상세 2개의 url이 매핑되어있습니다.
테스트
Application.java를 실행하면 자체 서버가 뜹니다.
2016-10-07 15:20:52.554 INFO 4148 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/list],methods=[GET]}" onto public java.util.List net.donnert.spring.boot.web.ArticleController.test()
2016-10-07 15:20:52.556 INFO 4148 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/article/{seq}],methods=[GET]}" onto public net.donnert.spring.boot.web.Article net.donnert.spring.boot.web.ArticleController.detail(long)
2016-10-07 15:20:52.561 INFO 4148 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-10-07 15:20:52.562 INFO 4148 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-10-07 15:20:52.611 INFO 4148 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-10-07 15:20:52.611 INFO 4148 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-10-07 15:20:52.758 INFO 4148 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-10-07 15:20:53.325 INFO 4148 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-10-07 15:20:53.686 INFO 4148 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
스프링 부트 스타터 웹에는 톰캣이 내장되어있습니다.
내장 톰캣이 8080으로 뜨는걸 볼 수 있습니다.
브라우저를 열고 url을 입력합니다.(http://localhost:8080/list)
[{"seq":1,"title":"This is title","text":"This is text","writer":"I am writer"},{"seq":2,"title":"This is title","text":"This is text","writer":"I am writer"},{"seq":3,"title":"This is title","text":"This is text","writer":"I am writer"},{"seq":4,"title":"This is title","text":"This is text","writer":"I am writer"},{"seq":5,"title":"This is title","text":"This is text","writer":"I am writer"},{"seq":6,"title":"This is title","text":"This is text","writer":"I am writer"},{"seq":7,"title":"This is title","text":"This is text","writer":"I am writer"},{"seq":8,"title":"This is title","text":"This is text","writer":"I am writer"},{"seq":9,"title":"This is title","text":"This is text","writer":"I am writer"},{"seq":10,"title":"This is title","text":"This is text","writer":"I am writer"}]
article 10개가 json형식으로 변환되어서 출력되는 것이 보입니다.
브라우저를 열고 url을 입력합니다.(http://localhost:8080/article/3)
{"seq":3,"title":"This is title","text":"This is text","writer":"I am writer"}
3번 article 역시 json으로 보여지고 있습니다. @PathVariable를 통해 url의 파라메터를 가져왔습니다.
간단하게 api서버가 완성(?)되었습니다.
logback, mybatis연결 등은 배치 예제에서와 동일한 방법으로 하시면 됩니다.
yml을 이용한 프로파일 적용 역시 동일합니다.
2016/09/23 - [개발/JAVA] - 스프링 부트(Spring boot)에서 mybatis(oracle) 적용하기