Spring을 공부하며 ioc와 di 그리고 bean에대해 많이 들어봤을 것이다.
처음에는 뭔지도 모르고 사용하기도 했다. 그래서 오늘은 간단하게라도 개념을 짚어보고자 한다.
1. Bean
- Ioc가 관리하는 자바 객체
@component, @service, @repository, @controller 같은 주석을 통해 구성 및 정의.
사용 방법은 아래 확인.
2. IOC (Inversion Of Control)
- 제어의 역전객체를 제어하고 관리하는 역할이 개발자로부터 스프링 컨테이너에 역전 된다는 뜻이다.
- 기존에는 구현 객체가 스스로 필요한 서버 구현 객체를 생성하고 연결했지만, 스프링 컨테이너를 사용하면 프로그램에 대한 제어 흐름에 대한 권한은 모두 스프링 컨테이너가 가지게 된다. 아래 예시를 들어보겠다.
----- Ioc 사용 이전 -----
public class UserService {
private UserRepository userRepository;
public UserService() {
this.userRepository = new UserRepository(); // creating UserRepository object directly
}
public User getUserById(long id) {
return userRepository.getUserById(id); // using UserRepository object directly
}
// other methods that use userRepository
}
----- Ioc 사용 -----
@Service
public class UserService {
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository; // userRepository is injected by Spring
}
public User getUserById(long id) {
return userRepository.getUserById(id); // using injected userRepository
}
// other methods that use userRepository
}
@Service로 UserService 클래스에 주석을 달았는데, 이는 이 클래스가 IoC 컨테이너에 의해 관리되어야 함을 Spring에 나타낸다.
3. Di (Dependency Injection) - 의존성 주입
- (autowired) 인스턴스를 직접 만들지 않고도 클래스 사용 가능.
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
// ...
}
@Autowired 주석을 사용하여 UserService 클래스에 주입. 이런 식으로 UserService 클래스는 인스턴스를 직접 만들지 않고도 UserRepository 클래스 사용 가능.
'TIL' 카테고리의 다른 글
AWS - EC2, RDS 내 SpringBoot 프로젝트와 연결하기 (0) | 2023.03.18 |
---|---|
다양한 Exception 커스텀하는 방법. (0) | 2023.03.16 |
Usecase - 유스케이스 다이어그램 (0) | 2023.02.27 |
자바 - 약한 결합 및 약한 의존성 (0) | 2023.02.25 |
자바 - 객체지향 프로그래밍의 4가지 특징 (캡슐화, 추상화, 상속, 다형성) (0) | 2023.02.23 |