본 게시물은 김영한 선생님의 강의를 학습하며 작성하였습니다.
옵션 처리
주입할 스프링 빈이 없어도 동작해야 할 때가 있다.
그런데 @Autowired
만 사용하면 required
옵션의 기본값이 true
로 되어 있어서 자동 주입 대상이 없으면 오류가 발생한다.
자동 주입 대상을 옵션으로 처리하는 방법은 다음과 같다
@Autowired(required=false)
: 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨org.springframework.lang.@Nullable
: 자동 주입할 대상이 없으면 null이 입력된다.Optional<>
: 자동 주입할 대상이 없으면Optional.empty
가 입력된다.
package com.hello.core.autowired;
import com.hello.core.member.Member;
import jakarta.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Optional;
public class AutowiredTest {
@Test
void AutowiredOption() {
ApplicationContext ac = new AnnotationConfigApplicationContext(TestBean.class);
}
static class TestBean {
@Autowired(required = false)
public void setNoBean1(Member noBean1){
System.out.println("noBean1 = " + noBean1);
}
@Autowired
public void setNoBean2(@Nullable Member noBean2){
System.out.println("noBean2 = " + noBean2);
}
@Autowired
public void setNoBean3(Optional<Member> noBean3){
System.out.println("noBean3 = " + noBean3);
}
}
}
'Backend > Spring' 카테고리의 다른 글
[섹션 7] 롬북과 최신 트랜드 (0) | 2024.03.18 |
---|---|
[섹션 7] 생성자 주입을 선택해라 (0) | 2024.03.18 |
[섹션 7]의존관계 자동 주입 - 다양한 의존관계 (0) | 2024.03.18 |
[섹션 6]컴포넌트 스캔 (0) | 2024.03.18 |
[섹션 5] @Configuation과 싱글톤 (0) | 2024.03.18 |