이모저모

의존관계 자동 주입 본문

coding/Java, Spring

의존관계 자동 주입

Jeo 2022. 2. 16. 22:11

from 김영한님의 스프링 핵심원리 기본편

 

의존관계 주입의 4가지 방법

1. 생성자를 통한 주입 

  • 생성자 호출시점에 딱 1번만 호출되는 것이 보장됨
  • 불변, 필수 의존관계에 사용 (이런 제약을 잘 설정해두는 것이 개발에서 중요하다.)
  • 단, 생성자가 딱 1개만 있는 경우에만 @Autowired 생략 가능

2. 수정자 주입(setter 이용) 

  • set~~~ (ex. setMemberRepository) 메서드를 이용
  • 선택, 변경 가능성이 있는 의존관계에 사용
  • 주입할 대상이 없어도 동작하게 하려면(즉 이건 필수값이 아니라고 하고 싶다면) => @Autowired(required = false) 

3. 필드 주입 

  • field injection is not recommended 
  • 왜? 외부에서 변경이 불가능. 변경을 위해서 다시 setter 만들어주어야 하는 등의 번거로움(?) 
  • 테스트 코드와 같은 특수한 경우 외에는 쓰지 말기

4. 일반 메서드 주입

  • 메서드 위에 autowired 라는 점에서 수정자 주입과 유사
  • 한번에 여러 필드 주입 가능
  • 잘 사용하지 않음

옵션 처리

- 주입할 스프링 빈이 없어도 동작해야 할 때.

package hello.core.autowired;
import hello.core.member.Member;
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 org.springframework.lang.Nullable;
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 // 호출은 하고 싶을 수도 있어. null 인 것을 확인하고 null 이면 default 넣어주고 싶다든지.
        public void setNoBean2(@Nullable Member noBean2) {
            System.out.println("noBean2 = " + noBean2);
        }
        
        @Autowired // java 8에서 제공하는 optional 문법.
        public void setNoBean3(Optional<Member> noBean3) {
            System.out.println("noBean3 = " + noBean3);
        }

    }
}

'coding > Java, Spring' 카테고리의 다른 글

request scope와 provider, proxy  (0) 2022.02.17
bean 등록시 자동/수동 선택 기준  (0) 2022.02.17
조회된 bean이 2 개 이상일 경우 해결방법  (0) 2022.02.16
singleton container  (0) 2022.02.16
ORM, JPA, Spring Data JPA  (0) 2022.02.16
Comments