의존관계 자동 주입
다양한 의존관계 주입 방법
옵션 처리
@Autowired(required=false)
: 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨org.springframework.lang.@Nullable
: 자동 주입할 대상이 없으면 null이 입력된다.Optional<>
: 자동 주입할 대상이 없으면 Optional.empty
가 입력된다.생성자 주입
롬복과 최신 트랜드
@Component
@RequiredArgsConstructor //<- Lombok 제공
public class OrderServiceImpl implements OrderService {
private final MemberRepository memberRepository;
private final DiscountPolicy discountPolicy;
}
@Autowired 필드 명, @Qualifier, @Primary
@Primary
가 우선권을 가진다.애노테이션 직접 만들기
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Qualifier("mainDiscountPolicy")
public @interface MainDiscountPolicy {
}
조회한 빈이 모두 필요할 떄, List, Map
Map<String, DiscountPolicy>
: map의 키에 스프링 빈의 이름을 넣어주고, 그 값으로 DiscountPolicy
타입으로 조회한 모든 스프링 빈을 담아준다.List<DiscountPolicy>
: DiscountPolicy
타입으로 조회한 모든 스프링 빈을 담아준다.자동, 수동의 올바른 실무 운영 기준