티스토리 뷰
- 이전 글에서 만든 Service, Repository에는 Controller에서부터 시작된 JdbcTemplate를 직접 넣어주었다.
- 여기서 UserController에 관해 몇 가지 의문점이 나올 수 있다.
● 의문점
1. static이 아닌 코드를 사용하려면 인스턴스화가 필요하다
- 일반적으로 JAVA에서 static이 붙지 않은 class를 사용하려면 먼저 해당 class의 instance를 만들어야한다.
- 하지만 위의 사진에서 볼 수 있듯이 UserController의 Constructor(생성자)는 만들었지만 그 어디에도 해당 Constructor를 이용해 UserController의 instance를 만든적은 없다.
- 그렇다면 도대체 어디에서 UserController의 instanc를 만든 것일까?
UserController userController = new UserController(jdbcTemplate); => 이렇게 작성한 적이 한 번도 없다.
2. 어떻게 UserController는 JdbcTemplate을 가져올 수 있었을까?
- UserController의 Constructor는 JdbcTemplate을 필요로 한다. 즉, UserController는 JdbcTemplate에 의존하고 있다.
- 다른 말로하면 UserController는 JdbcTemplate이 없으면 동작하지 않는다는 의미이다.
- 문제는 현재 그 어떤 곳에도 JdbcTemplate이란 class를 설정하거나 instance를 만든 적이 없다는 것이다.
3. 번거롭게 Controller에서부터 JdbcTemplate를 넣어주지 말고 Repository에서 바로 JdbcTemplate를 가져올 수는 없나?
● @RestController
- 의문점에 대한 답은 바로 @RestController Annotation에 있다.
@RestController의 기능
1. @RestController Annotation이 붙은 class를 API 진입 지점으로 만들어준다.
2. 해당 class를 Spring bean으로 등록시킨다.
● Spring bean
1번 질문 해결
- Spring boot로 만들어진 서버가 시작되면 스프링 서버 내부에 거대한 컨테이너가 만들어지고 이 컨테이너 안에는 여러 class들이 자동으로 들어가게 된다.(Spring Container 안으로 들어간 class를 Spring bean이라고 한다.)
- 이때 다양한 정보들도 함께 들어가고 & 인스턴스화도 이루어진다.
- 한편 Spring Container에서 UserController를 인스턴스화 하려면 JdbcTemplate도 함께 필요한데 사실 JdbcTemplate도 이미 Spring bean으로 등록되어 있다.
- 즉, UserController와 JdbcTemplate 모두 Spring Container 안에 있으니 UserController를 인스턴스화 할 때 JdbcTemplate를 넣어줄 수 있는 것이다.(필요한 의존성이 자동으로 설정된다.)
- 다르게 말하면 Spring Container는 서로 필요한 관계의 클래스(bean)들을 연결해주는 역할을 수행하고 있는 것이다.
2번 질문 해결
- 그렇다면 JdbcTemplate은 누가 어디서 Spring bean으로 등록한 것일까?
- 이는 미리 설정해 놓은 외부 의존성 덕분이다.(Dependency가 미리 등록해주고 있었다.)
cf) 의존성 : 프로젝트에서 사용하는 라이브러리, 프레임워크 등을 의미
- 즉, build.gradle에 spring-boot-starter-data-jpa가 있었기에 해당 의존성이 특정 라이브러리 or 프레임워크를 가져왔고(build.gradle을 통해 Dependency(의존성)를 설정)
- 그 라이브러리 or 프레임워크 안에 JdbcTemplate을 Spring bean으로 등록해주는 코드가 있었고
- 그 덕분에 UserController에서 JdbcTemplate을 바로 가져올 수 있었던 것이다.
- 실제로 build.gradle에서 JdbcTemplate와 관련된 Dependency를 주석 처리하니 빨간 줄이 떴다.
3번 질문 해결
- UserRepository가 Spring bean이 아니라면 바로 JdbcTemplate을 가져올 수는 없다.
- 즉, JdbcTemplate을 바로 가져오려면 UserRepository가 Spring bean이어야 하는데 현재 UserRepository는 Spring bean이 아니다.
- 그렇다면 UserRepository에서 JdbcTemplate을 바로 가져올 수 있게 UserRepository를 Spring bean으로 등록해보자
- 하는 김에 UserService도 Spring bean으로 등록해 보자
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository {
private final JdbcTemplate jdbcTemplate;
// UserRepository와 JdbcTemplate 모두 bean으로 등록돼 있기에 알아서 넣어준다.
public UserRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
......
}
import com.group.libraryapp.repository.user.UserRepository;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
// UserRepository가 bean으로 등록돼 있기에 알아서 넣어준다.
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
......
}
import com.group.libraryapp.service.user.UserService;
import org.springframework.web.bind.annotation.*;
@RestController
public class UserController {
private final UserService userService;
// UserService가 bean으로 등록돼 있기에 알아서 넣어준다.
public UserController(UserService userService) {
this.userService = userService;
}
......
}
0. JdbcTemplate을 Spring bean으로 등록
1. JdbcTemplate을 의존하는 UserRepository가 Spring bean으로 등록
2. UserRepository를 의존하는 UserService가 Spring bean으로 등록
3. UserService를 의존하는 UserController가 Spring bean으로 등록
'Backend > Spring' 카테고리의 다른 글
#21 Spring bean을 등록하는 방법 / Spring bean을 주입 받는 방법 (0) | 2023.09.03 |
---|---|
#20 Spring Container 사용 이유 with @Primary, IoC, DI (0) | 2023.08.31 |
#18 Clean Code - Controller, Service, Repository 분리 (0) | 2023.08.24 |
#17 Clean Code (0) | 2023.08.21 |
#16 MySQL - UPDATE, DELETE 예외 처리 (0) | 2023.08.20 |
- Total
- Today
- Yesterday
- MongoDB
- 코테
- API
- Phaser
- db
- Spring Boot
- nosql
- SQL
- 알고리즘
- SpringBoot
- Java8
- 코딩테스트
- git
- Phaser3
- 빅데이터 분석기사
- 빅데이터
- 메모리
- 자료구조
- 프로세스
- 프로그래머스
- Advanced Stream
- node.js
- spring
- OS
- Stream
- DART
- jpa
- MySQL
- 운영체제
- java
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |