1. 시작
오늘은 스프링 부트를 이용하여 간단한 웹 페이지를 만들어보려고 한다. 만약 스프링에 대한 이해가 필요하다면 우선 Spring Framework 5분만에 이해하기를 읽어보자.
2. Spring Tool Suite 설치
STS는 스프링 개발에 최적화된 도구이다. 그러면 먼저 Spring Tool Suite™을 설치해 보자. https://spring.io/tools 에서 받을 수 있는데, 리눅스용, 맥용(dmg 파일), 윈도우용 다양하게 제공된다.
필자는 d:\spring 폴더에 다운받은 파일을 놓고 압축을 풀어보았다. D:\spring\spring-tool-suite-3.8.4.RELEASE-e4.6.3-win32\sts-bundle\sts-3.8.4.RELEASE
디렉토리 안에 STS라는 실행 파일이 생긴다. 이 파일을 실행하면 Spring Tool Suite가 실행된다. Workspace를 잡아줘야 하는데 원하시는 곳으로 잡으면 된다. 필자는 그냥 d:\spring\workspace로 했다. 그러면... 이클립스와 유사한 스크린을 만날 수 있다!!
3. 프로젝트 생성
NEW -> Spring Starter Project 선택 후 이름 적고, 자바 버전 적고 진행한다. 그리고 디펜던시에는 Web, DevTools 추가한다. 일단 이유는 묻지 말자!
4. 인덱스 페이지 생성
src/main/resources/static 에 index.html 파일을 만든다다. 내용은 알아서.. 예를 들어 "My Spring Boot Test"라고 적는다.
참고로 뒷단계에서 아무것도 안하고 Spring Boot 실행을 하고 http://localhost:8080에 연결하면 Whitelabel Error Page가 출력된다.
5. 컨트롤러 생성
내 패키지 하위에 컨트롤러를 만들어야 한다.. 예를 들어 com.my.sample 패키지에 IndexController를 만든다. 제가 만든 소스 내용이다.
package com.my.sample; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class IndexController { @RequestMapping("/hello") public @ResponseBody String hello() { return "Hello, Spring Boot!"; } }
6. 포트 설정
브라우저에서 접속하기 위한 포트를 정의하는 부분이다. 기본은 8080 인데.. src/main/resources/application.properties 파일에서 수정하면 된다. 8000으로 바꿔보겠다.
server.port = 8000
7. 실행
Run As -> Spring Boot App으로 실행한다. 그러면 STS 콘솔에 로그가 기록되기 시작한다.
16:41:32.709 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : [] 16:41:32.711 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/] 16:41:32.711 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/D:/spring/workspace/my-boot-sample-1/target/classes/] . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.4.RELEASE) 2017-06-23 16:41:32.971 INFO 2824 --- [ restartedMain] com.my.sample.MyBootSample1Application : Starting MyBootSample1Application on jinschoi-PC with PID 2824 (D:\spring\workspace\my-boot-sample-1\target\classes started by jinschoi in D:\spring\workspace\my-boot-sample-1) 2017-06-23 16:41:32.972 INFO 2824 --- [ restartedMain] com.my.sample.MyBootSample1Application : No active profile set, falling back to default profiles: default 2017-06-23 16:41:33.023 INFO 2824 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@26229e: startup date [Fri Jun 23 16:41:33 KST 2017]; root of context hierarchy 2017-06-23 16:41:34.122 INFO 2824 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8000 (http) 2017-06-23 16:41:34.131 INFO 2824 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2017-06-23 16:41:34.132 INFO 2824 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15 2017-06-23 16:41:34.209 INFO 2824 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2017-06-23 16:41:34.209 INFO 2824 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1188 ms 2017-06-23 16:41:34.359 INFO 2824 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2017-06-23 16:41:34.362 INFO 2824 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2017-06-23 16:41:34.363 INFO 2824 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2017-06-23 16:41:34.363 INFO 2824 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2017-06-23 16:41:34.363 INFO 2824 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2017-06-23 16:41:34.626 INFO 2824 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@26229e: startup date [Fri Jun 23 16:41:33 KST 2017]; root of context hierarchy 2017-06-23 16:41:34.682 INFO 2824 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.String com.my.sample.IndexController.hello() 2017-06-23 16:41:34.685 INFO 2824 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.map<java.lang.string, java.lang.object="">> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2017-06-23 16:41:34.686 INFO 2824 --- [ restartedMain] 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) 2017-06-23 16:41:34.706 INFO 2824 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-06-23 16:41:34.707 INFO 2824 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-06-23 16:41:34.740 INFO 2824 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-06-23 16:41:34.758 INFO 2824 --- [ restartedMain] oConfiguration$WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html] 2017-06-23 16:41:34.853 INFO 2824 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2017-06-23 16:41:34.893 INFO 2824 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-06-23 16:41:34.952 INFO 2824 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8000 (http) 2017-06-23 16:41:34.956 INFO 2824 --- [ restartedMain] com.my.sample.MyBootSample1Application : Started MyBootSample1Application in 2.234 seconds (JVM running for 2.946)
8. 접속
브라우저에서 http://localhost:8000/ 로 접속하면 "My Spring Boot Test"가 뜬다.
-> index.html
브라우저에서 http://localhost:8000/hello 로 접속하면 "Hello, Spring Boot!"가 뜬다.
-> IndexController.java
9. DB Connection Pool
참고로 Spring Boot 1.x 버전의 기본 Connection Pool은 Tomcat용이고, 2.x 버전의 기본은 HikariCP이다.
다음은 Connection Pool 예제이다.
spring.datasource.url= spring.datasource.username= spring.datasource.password= spring.datasource.driver-class-name= spring.datasource.schema= spring.datasource.data= spring.datasource.initial-size= spring.datasource.max-active= spring.datasource.max-idle= spring.datasource.min-idle=
10. STS를 통해 쉽게 프로젝트 생성
STS 실행 후 New -> New Spring Starter Projet를 통해 쉽게 프로젝트를 생성할 수 있습니다. (STS 기준)
Name, Group 등을 잡고 나서는 Next로 넘어가 디펜던시를 잡아주면 되는데요, Web Starter 추가하시면 가장 기본적인 것은 사용할 수 있어요.
Web Starter만 추가한 상태에서 실행을 하고 http://localhost:8080에 연결하면 Whitelabel Error Page가 출력됩니다. 앞에서 했던 것처럼 다음을 추가해 보지요.
@RequestMapping("/hello") public @ResponseBody String hello() { return "Hello, Spring Boot"; }
11. Spring Boot의 Servlet 설정
Spring Boot에서 Servlet 설정 시 @webservlet 등 어노테이션을 이용하여 설정할 수 있다. 또한 Spring Boot에서 제공한 class로 설정할 수 있다.
어노테이션으로 설정이 안되는 것은 application.properties 통해 설정한다.