Setting Up Spring Boot Project
Database 의 기본적인 설정을 마친 이후에 Spring Boot Project 에 본격적으로 들어가보도록 하자.
Automatic Data Source Configuration
Hibernate 는 Spring Boot 의 JPA default implementation 이라는 점을 위에서 살펴보았다.
EntityManager 는 Hibernate 의 일부분으로써, query 의 생성 등을 담당하는 main component 이다. EntityManager, DataSource 들은 명시적으로 @Component 등의 annotation 이 설정되어 있지 않지만, Spring Boot 의 Auto-configuration 에 따라서 자동으로 Bean 이 생성된다.
이후에 이 Bean 들을 Application 의 DAO 등에 injection 하여 사용할 수 있다. DAO 는 Database 와 Application 의 상호작용을 담당하는 obejct 이다. 더 자세한 내용은 나중에 알아보자.
Setting up Project with Spring Initializr
Spring Initializr 에서 다음 두 개의 dependency 를 추가해야 한다.
- MySQL Driver:
mysql-connector-j- Spring Data JPA:
spring-boot-starter-data-jpa
Spring Boot - Auto Configuration
Spring Boot 는 Maven POM file 을 기반으로 automatic 하게 data source 를 설정해줄 것이다.
DB connection 의 경우, application.properties 파일을 통하여 설정할 수 있다. 아래와 같이 작성하면 된다.
spring.datasource.url=jdbc:mysql://localhost:3306/student_tracker
spring.datasource.username=springstudent
spring.datasource.password=springstudentspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 를 통하여 JDBC driver class name 을 지정해주지 않아도 Spring Boot 가 알아서 자동으로 URL 을 통하여 MySQL 임을 파악한다.
Creating Spring Boot - Command Line App
우선 Hibernate / JPA 에 집중하기 위하여 Application 을 Command Line 기반으로 생성해보자. 이후에 CRUD REST API 를 사용하여 발전시킬 것이다.
다음 코드를 살펴보자.
@SpringBootApplication
public class CrudDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CrudDemoApplication.class, args)
}
@Bean
public CommandLineRunner commandLineRunner(String[] args) {
return runner -> {
System.out.println("Hello World");
};
}
}CommandLineRunner 는 Application 이 시작된 이후에 특정 코드를 실행할 수 있도록 제공되는 Interface 이다. 이를 implement 하면 Spring Boot Application 의 구동 시점에 원하는 작업 등을 수행할 수 있다.
run() method 는 Application 이 완전히 시작되기 전에 실행된다. run() method 의 진행 과정에서 ApplicationContext 가 먼저 초기화되고, 모든 Bean 들이 생성되고 초기화된 이후에 CommandLineRunner 의 코드들이 실행된다.