You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
섹션7. 의존 관계 자동 주입
1. 다양한 의존 관계 주입 방법
생성자 주입
생성자를 통해서 의존 관계를 주입 받는 방법 (지금까지 우리가 진행한 방법)
수정자 주입(setter)
필드의 값을 변경하는 수정자 메서드인 setter를 통해서 의존관계를 주입하는 방법
필드 주입
필드에 바로 주입하는 방법
( 테스트 코드, 스프링 설정을 목적으로 하는 @configuration 같은 곳에서만 특별히 사용)
일반 메서드 주입
일반 메서드를 통해 주입받는 방법
2. 옵션 처리
주입할 스프링 빈이 없어도 동작해야 할 때가 있다.
그런데
@Autowired만 사용하면 required 옵션의 기본값이 true로 되어 있어 자동 주입 대상이 없으면 오류가 발생한다.자동 주입 대상을 옵션으로 처리하는 방법
@Autowired(required = false): 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출되지 않는다.org.springframework.lang.@Nullable: 자동 주입할 대상이 없으면 null이 입력된다.Optional<>: 자동 주입할 대상이 없으면 Optional.empty가 입력된다.3. 생성자 주입을 선택해라!
최근에는 스프링을 포함한 DI 프레임워크 대부분이 생성자 주입을 권장한다.
불변
누락
final 키워드
정리
4. 롬복과 최신 트렌드
기본 코드
생성자가 1개 이므로
@Autowired생략@RequiredArgsConstructorfinal이 붙은 필드를 모아서 생성자를 자동으로 만들어주는 기능
정리
생성자를 하나만 둬서 @Autowired를 생략, lombok 라이브러리의 @requiredargsconstructor 함께 사용하여 깔끔하게 모든 기능을 다 제공한다.
All reactions