스프링 부트 원리 (1)
의존성 관리 이해
- spring-boot-dependencies -> spring-boot-starter-parent -> 내 프로젝트의 pom 순으로 의존성 계층 구조가 성립
- spring-boot-dependencies의 dependencyManagement에 각종 의존성들에 대한 version이 모두 명시되어 있음
- 따라서 내 프로젝트의 pom에 spring-boot-dependencies에 정의되어 있는 의존성을 사용하게 될 경우, 직접 version을 명시해주지 않더라도 version 정보를 가져오게 됨
- 즉, 각각의 starter에 이미 의존성들이 제공되고 있기 때문에 우리가 직접 관리해야 할 의존성의 수가 줄어들게 됨
- 우리가 관리해야 하는 일이 줄어든다는 의미
- version up을 하고자 할 때, third-party library의 어느 version과 호환되는지 모르는 문제도 해결 가능
- 깔끔한 의존성 관리
- pom에서 지원하지 않는 의존성을 추가하고자 할 때는 직접 version을 명시해주어 함!
- 특정 library의 특정 version의 사용을 원하는 경우 명시해주어 사용 가능 -> 편리한 Customizing
- 자기만의 의존 구조를 성립시키고 싶을 때는? (두 가지 방법)
- 직접 parent pom을 만들어 현재 프로젝트의 parent로 만들고, 그 parent로 spring-boot-starter-parent를 두는 것 (추천)
- 즉, spring-boot-starter-parent -> 내 프로젝트의 parent -> 내 프로젝트의 구조를 만드는 것
- 현재 프로젝트의 parent를 만들고, 해당 parent에 섹션을 만들어 spring-boot-starter를 추가하여 사용 (비추천)
- but, spring-boot-starter에는 dependency들만 가져오는 것이 아니라, 그 밖의 다른 설정들이 존재
- ex) java 1.8, UTF-8, 각종 yml, plugin 설정 등
- 이 설정들을 가져오지 못하는 불편함 존재
의존성 관리 응용
-
- 버전 관리 해주는 의존성 추가
- spring-boot-starter-data-jpa
-
- 버전 관리 안해주는 의존성 추가
- ModelMapper: version을 명시해주어야 함
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.1</version>
</dependency>
# Source model
class Order {
Customer customer;
Address billingAddress;
}
class Customer {
Name name;
}
class Name {
String firstName;
String lastName;
}
class Address {
String street;
String city;
}
# Destination model
class OrderDTO {
String customerFirstName;
String customerLastName;
String billingStreet;
String billingCity;
}
# Domain to DTO를 자동으로 해주는 기능!
ModelMapper modelMapper = new ModelMapper();
OrderDTO orderDTO = modelMapper.map(order, OrderDTO.class)
-
- 기존 의존성 버전 변경하기
- 내 프로젝트 pom의 에 직접 명시해주어 변경 가능!
<properties>
<spring.version>5.0.6.RELEASE</spring.version>
<java.version>1.9</java.version>
</properties>
자동 설정 이해
- @Configuration?
- SpringBootApplication의 핵심 annotation들!
- @SpringBootConfiguration
- @ComponentScan
- @EnableAutoConfiguration
- 스프링 부트는 Bean을 두 번 등록
- ComponentScan으로 한 번
- EnableAutoConfiguration으로 또 한 번
- 1단계: @ComponentScan
- @Component을 달고 있는 class들을 Scan해서 Bean으로 등록
- @Configuration, @Repository, @Service, @Controller, @RestController 들도!
- 2단계: @EnableAutoConfiguration
- springframework.boot.autoconfigure.EnableAutoConfigure 내 META-INF의 spring.factories 파일 읽어옴
- 그 아래의 @Configuration들 읽어옴
- but, @ConditionalOn'XxxYyyZzz'
- 즉, 조건에 따라 Bean으로 등록하기도 하고, 안하기도 함!