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.
7_의존관계 자동 주입 (1)
다양한 의존관계 주입 방법
생성자 주입
@Autowired생략 : 생성자가 1개만 존재한다면 생략 가능하다 (스프링 빈에만 해당)@Autowired가 있는 것과 같게 취급하는 의미수정자 주입 (Setter 주입)
@Autowired애노테이션을 추가해야 한다.@Autowired를 사용할 때, 주입할 대상이 없으면 오류가 발생한다.@Autowired(required=flase)로 지정해야 한다.필드 주입
@Configuration같은 곳에서만 특별한 용도로 사용하는 것이 좋다.@Autowired가 동작하지 않는다. 스프링 빈이기때문에 작동하는 것임을 주의해야 한다.일반 메서드 주입
옵션 처리
주입할 스프링 빈이 없어도 동작해야 할 때가 있다.
@Autowired만 사용하면 required 옵션의 기본값이 true로 되어 있어서 자동 주입 대상이 없으면 오류 발생자동 주입 대상을 옵션으로 처리하는 방법 3가지
@Autowired(requied=false): 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출이 안됨org.springframework.lang.@Nullable: 자동 주입할 대상이 없으면 null이 입력됨Optional<>: 자동 주입할 대상이 없으면 Optinal.empty가 입력됨예제 코드 추가
AutowiredTest.java생성자 주입을 선택해라!
불변
누락
final 키워드
final키워드를 사용할 수 있다.롬복과 최신 트랜드
편리를 위해 롬복 사용
롬복 라이브러리 적용 방법
build.gradle에 라이브러리 및 환경 추가롬복 사용 전 코드
롬복 사용
@RequiredArgsConstructor기능을 사용하면 final이 붙은 필드를 모아서 생성자를 자동으로 만들어준다.롬복 사용 후 코드
정리
@Autowired를 생략하는 방법을 주로 사용@RequiredArgsConstructor함께 사용하면 기능은 다 제공하면서, 코드를 간결하게 쓸 수 있음All reactions