탑크리에듀(www.topcredu.co.kr)제공 스프링 프레임워크 강좌중 스프링 부트에 대한 소개 및 스프링부트에서 DB의 테이블 또는 데이터를 초기화 할 수 있는 방법에 대해 설명한 자료 입니다. 본원 웹사이트에 오시면 스프링 프레임워크, 스프링 부트, JPA, Querydsl 관련 다양한 무료 동영상 강좌들이 있으니 살펴 보시면 좋을 듯 합니다.
2. xamarin.android 2.3 hello android multi screen example part2
(스프링부트소개및 Spring Boot에서 데이터베이스 초기화 방법)_추천자바재직자학원/스프링재직자학원/JPA재직자교육/SQL근로자카드교육
1. 탑크리에듀교육센터(www.topcredu.co.kr, www.ojc.asia) 1
스프링 부트(Spring Boot)
소개 및 DB초기화
1. 스프링 부트(Spring Boot)....................................................................................................................................... 2
1-1. Spring Boot 소개.................................................................................................................................................... 2
1-2. Spring Boot & Maven .......................................................................................................................................... 2
1-3. Spring Boot & Gradle........................................................................................................................................... 3
1-4. Writing the code(Spring Boot main) ............................................................................................................. 4
1-5. Writing the code(CommandLineRunner)..................................................................................................... 5
1-6. Spring Boot 에서 property 파일 읽기.......................................................................................................... 6
1-7. 스프링 부트, JPA 에서 데이터베이스 초기화............................................................................................ 7
2. 탑크리에듀교육센터(www.topcredu.co.kr, www.ojc.asia) 2
1. 스프링 부트(Spring Boot)
1-1. Spring Boot 소개
스프링 응용프로그램을 독립적으로 작성, 빌드, 실행할 수 있으며 Embedded Tomcat, Jetty 사용이
가능하므로 WAR 파일로 묶어서 배포할 필요가 없다.
Tomcat이나 Jetty가 내장되어 웹 프로젝트 띄우는 시간이 독립적인 Tomcat을 이용하는 경우에 비
해 훨씬 줄어든다. 이렇게 서블릿 컨테이너가 내장되어 있으므로 프로젝트를 .jar 파일 형태로 간
단히 만들어 배포할 수 있다.
스프링 부트를 사용하면 메이븐의 pom.xml에서 의존하는 라이브러리의 버전을 일일이 지정하지
않아도 된다. 즉 스프링 부트가 라이브러리 및 버전을 알아서 관리한다.
스프링에서는 XML 파일 또는 JavaConfig 등을 이용하여 설정을 하는데 스프링 부트에서는 XML
설정이 필요없고 모든 설정을 다 자동화 하지는 않지만 스프링 프레임워크를 시작할 수 있을 정
도는 가능하다.(Application.java)
Spring Tool Suit(STS)를 사용하지 않고도 간단히 스프링 프로젝트를 만들 수 있다.
파이썬(python)의 flask, 장고(django) 나 ruby on rails 처럼 빠르게 웹 프로젝트를 만들 수 있는
도구이다.
2017년 1월 현재 버전은 1.4.3 이다.
1-2. Spring Boot & Maven
메이븐 설정을 위해 “starter” POMS를 제공한다.
(Spring Boot에서 미리 정의된 MAVEN Dependency)
메이븐에서 사용하려면 <parent>태그로 spring-boot-starter-parent를 상속받아야 하며 기본자바
컴파일러는 스프링 부트 1.4인 경우 java version은 1.7이며 아래처럼 별도로 설정 할 수 있다.
<properties>
<java.version>1.8</java.version>
</properties>
spring-boot-starter-web을 추가하면 Tomcat 및 Spring MVC 가 자동 추가된다.
<!-- Inherit defaults from Spring Boot -->
<!—UTF-8지원, spring-boot-dependencies POM으로 상속되는 공통디펜던시에 대한 version 태
그 생략가능, application.properties 및 application.yml을 위한 리소스 필터링등을 제공
<parent>
<groupId>org.springframework.boot</groupId>
3. 탑크리에듀교육센터(www.topcredu.co.kr, www.ojc.asia) 3
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!—실행가능한 JAR 파일 패키징, WAR아카이브 지원하며 그안에서 응용프로그램을 실행한다. -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
메이븐 Starter POM은 응용프로그램에 포함시킬 수 있는 편리한 Depency 설정을 지원하는데
WEB을 이용한 개발을 하려면 spring-boot-starter-web, JPA를 사용하려면 spring-boot-starter-
data-jpa 만 디펜던시에 추가하면 되는데 spring-boot-starter-? 형태의 패턴이다.
1-3. Spring Boot & Gradle
Gradle에서 사용하려면 “stater POMs”를 직접 import하면 된다.
spring-boot-gradle-plugin은 실행 가능한 jar파일을 만들고 프로젝트를 실행할 수 있도록 task를
제공한다.
buildscript {
repositories {
jcenter()
}
dependencies {
4. 탑크리에듀교육센터(www.topcredu.co.kr, www.ojc.asia) 4
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.2.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'spring-boot'
repositories {
jcenter()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
1-4. Writing the code(Spring Boot main)
아래와 같이 main 함수를 만들면 된다.
//스프링부트 1.2 이상에서 @SringBootApplication 어노테이션은 아래 모든 어노테이션을 포함한다.
//클래스 패스를 기반으로 기본적인 동작을 지시하는데 tomcat-embed-core.jar이 클래스패스에 있다
면 톰캣서버가 적당한 기본값으로 설정 및 구성되고 spring-webmvc.jar 파일이 클래스패스에 존재하
면 Spring MVC의 DispatcherServlet이 자동으로 구성되고 등록된다. web.xml 역시 필요없다.
@EnableAutoConfiguration
@ComponentScan //현재 패키지를 기준으로 컴포넌트를 스캐닝, 빈, 서비스, 모델, DAO, 컨트롤러
@Configuration //현재 파일이 컨텍스트의 설정 파일임을 의미
public class DemoApplication{
public static void main(String[] args) throws Exception {
// Spring Boot의 SpringApplication.run() 메소드를 실행, 시작점
// 웹응용프로그램이면 자동 설정된 Tomcat 웹 서버를 기동하면서 응용프로그램을 시작한다
SpringApplication.run(DemoApplication.class, args);
}
}
[실행 방법]
1. (DOS에서)프로젝트 루트에서 spring-boot-starter-parent의 run을 이용하여 Maven으로 실행한다.
D:..>mvn spring-boot:run
5. 탑크리에듀교육센터(www.topcredu.co.kr, www.ojc.asia) 5
2. 이클립스(STS) 프로젝트 루트 -> Run as -> Maven Build 또는 Java Application(main이 있는
Application클래스 지정)
3. 이클립스(STS) main이 있는 Application클래스에서 Run as -> Spring Boot Application 또는 Java
Application으로 실행가능 하다.
1-5. Writing the code(CommandLineRunner)
스프링 부트를 시작할 때 Command Line arguments를 주거나, 어떤 코드를 실행하려면
CommandLineRunner 인터페이스의 run(String…args)를 구현하면 된다. 만약 CommandLineRunner
인터페이스 구현이 여러 개 있는 경우 순서를 부여하기 위해서는 @Order 어노테이션을 사용하면
된다.
@SpringBootApplication
public class CommandLineRunnerExam {
//Spring Boot 메인
public static void main(String... args) {
SpringApplication.run(CommandLineRunner.class, args);
}
}
class DefaultRunner implements CommandLineRunner {
//CommandLineRunner의 run 메소드 구현
//args는 메인 메소드의 아규먼트를 받아들인다.
public void run(String... args) throws Exception {
// joining(delimiter, prefix, suffix)
System.out.println(Arrays.asList(args).stream().collect(Collectors.joining(",",getClass().getSimpleName()
+ "[", "]"))); }
}
/*
java.util.stream패키지는 스트림에 대한 함수형 조작을 제공하고
Spring4에서 새로 소개된 @Order 어노테이션은 같은 타입의 빈이 컬렉션(List등)에 Autowired 될 때
그 순서를 지정한다.(낮은 숫자가 우선순위가 높다).
6. 탑크리에듀교육센터(www.topcredu.co.kr, www.ojc.asia) 6
*/
@Named
@Order(2)
class Runner1 extends DefaultRunner { }
@Named
@Order(1)
class Runner2 extends DefaultRunner { }
@Named
@Order(3)
class Runner3 extends DefaultRunner { }
[실행]
$ java -jar build/libs/commandlinerunner-exam-1.0.0.jar 이순신 안중근 유관순
Runner2[이순신 안중근 유관순]
Runner1[이순신 안중근 유관순]
Runner3[이순신 안중근 유관순]
1-6. Spring Boot에서 property 파일 읽기
[src/main/resources/ojc.properties]
url=ojc.asia
[Application.java]
@SpringBootApplication
@PropertySource("ojc.properties")
public class Application {
public static main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
7. 탑크리에듀교육센터(www.topcredu.co.kr, www.ojc.asia) 7
[OjcController.java]
@Controller
public class OjcController {
@Value("${url}") //ojc.properties 파일의 url을 값을 주입
String url;
@RequestMapping("/ojc")
public void home() {
System.out.println(url); //ojc.asia 출력
}
}
1-7. 스프링 부트, JPA에서 데이터베이스 초기화
스프링 부트에서는 클래스패스 경로에(src/main/resources등) schema.sql, data.sql, schema-
${platform}.sql, data-${platform}.sql 파일등이 존재한다면 자동으로 실행해서 스키마 구조와 데
이터를 초기화 시켜주는데. 만약 application.properties 파일에서
spring.datasource.platform=mysql 이라고 했다면 schema-${platform}.sql 파일의 이름은
schema-mysql.sql이 된다.
JPA는 시작시점에 DDL을 자동 생성 및 실행해 주는 기능이 있는데 두개의 외부 속성으로 정의한
다. spring.jpa.generate-ddl은 (boolean) on, off 값을 가지고 DB벤더에 종속적이지 않은반면
spring.jpa.hibernate.ddl-auto (enum)는 하이버네이트 특성으로 하이버네이트 Sessionfactory가 시
작할 때 JPA의 엔티티 매핑, 연관관계 설정을 기본으로 테이블과 같은 스키마 생성 스크립트를 만
들고 실행하여 데이터베이스 초기화를 지원하는데 열거형 값인 none, validate, update, create,
create-drop 값을 가진다.
hsqldb, h2 and derby 데이터베이스는 create-drop이 기본이며 그외 DB는 none이 기본값이다.
none : 자동 DDL 생성 안함.
create : 하이버네이트 Sessionfactory 가 시작될 때 항상 다시 생성, 이미 있다면 지우고 생성.
create-drop : Sessionfactory 가 시작될 때 생성 후 종료할 때 삭제한다.
update : Sessionfactory 가 시작될 때 엔티티 클래스(도메인 클래스)와 DB 에 생성된 스키마
구조를 비교해서 DB 쪽에 생성이 안된 테이블 또는 칼럼이 있다면 DB 스키마를 변경해서
생성시키지만 기 생성된 스키마 구조를 삭제하지는 않는다.