GDG on Campus Backend-Spring 스터디 WIL
Week 1 - Spring 프레임워크와 IOC/DI
Framework vs Library
Framework
- Inversion of Control (IoC): 프레임워크가 개발의 흐름을 제어한다.
- 프로젝트의 구조와 규칙을 제공한다.
Library
- 개발자가 코드 흐름을 제어한다.
- 특정 기능을 선택적으로 사용할 수 있다.
POJO (Plain Old Java Object)
- 특정 기술이나 환경에 구애받지 않는 단순한 자바 객체
- 스프링은 POJO를 이용하는 POJO-based enterprise framework 이다.
POJO의 조건
- 기존 class를 extend하지 않는다.
- 기존 interface를 implement하지 않는다.
- 기존 annotation을 포함하지 않는다.
스프링 삼각형(The Spring Triangle)
- IoC/DI (Inversion of Control/Dependency Injection)
- AOP (Aspect-Oriented Programming)
- PSA (Portable Service Abstraction)
Spring container에 원하는 객체를 요청하면, Spring container가 인스턴스를 반환한다.
What is Dependency?
클래스 A가 클래스 B의 메서드를 사용하면 의존성이 생긴다.
A는 의존하는 객체이고, B는 의존되는 객체이다.
java public class SimpleMovieLister { // SimpleMovieLister is tightly coupled with MovieFinder private final MovieFinder movieFinder; // The constructor creates a MovieFinder instance directly (not dependency injection) public SimpleMovieLister() { this.movieFinder = new MovieFinder(); // Directly depends on the MovieFinder implementation } }
SimpleMovieLister
클래스가MovieFinder
객체를 직접 생성하기 때문에 의존성이 높다.
public class SimpleMovieLister {
private final MovieFinder movieFinder;
@Autowired
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
* Spring 4.3부터 단일 생성자를 가진 클래스는 @Autowired
생략 가능
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
* Spring 4.3부터 단일 생성자를 가진 클래스는 @Autowired
생략 가능
Constructor-based vs Setter-based DI
- Constructor Injection: 필수 의존성 (Mandatory)
- Setter Injection: 선택적 의존성 (Optional)
Constructor Injection | Setter Injection | |
---|---|---|
Type of Dependency | 필수 | 선택 |
Injection Method | 생성자 | 메서드 |
생성 순서 | 대상 객체 -> 의존 객체 | 의존 객체 -> 대상 객체 |
효율성 | 빠름 | 느림 |
public class SimpleMovieLister {
@Autowired
private MovieFinder movieFinder;
}
Field injection은 NullPointerException, Immutability, Single Responsibility Violation, Circular Dependencies, 테스트의 어려움 등으로 인해 권장되지 않는다.