반응형

생성자 주입

  • 생성자 주입은 클래스의 생성자를 통해 의존성을 주입하는 방법이다.
  • 클래스의 필드에 대한 의존성을 외부에서 주입받을 때 주로 사용된다.
  • 클래스의 인스턴스를 생성할 때 필요한 모든 의존성을 생성자 매개변수로 전달받아 해당 필드에 할당한다.
  • 불변성과 필수성을 보장하고, 객체를 생성하는 시점에 모든 의존성이 주입되므로 안정적인 객체 생성을 할 수 있다.
  • 생성자가 딱 1개만 있으면 @Autowired를 생략해도 자동 주입 된다. 물론 스프링 빈에만 해당한다.

ex)

@Component
public class SpringServiceImpl implements SpringService {
    private final SpringRepository springRepository;

    // 생성자 주입
    @Autowired
    public SpringServiceImpl(SpringRepository springRepository) {
        this.springRepository = springRepository;
    }   
}

 

 

수정자 주입 (Setter Injection)

  • 수정자 주입은 클래스의 수정자(Setter) 메서드를 통해 의존성을 주입하는 방법이다. 
  • 클래스의 필드에 대한 의존성을 설정하는 메서드를 제공하여 외부에서 의존성을 주입한다.
  • 선택, 변경 가능성이 있는 의존관계일 때 사용하기 좋다.

ex) 

@Component
public class SpringServiceImpl implements SpringService {
    private SpringRepository springRepository;

    // 수정자 메서드
    @Autowired
    public void setSpringRepository(SpringRepository springRepository) {
        this.springRepository = springRepository;
    }

}

 

 

필드 주입 (Field Injection)

  • 필드 주입은 클래스의 필드에 직접 의존성을 주입하는 방법이다.
  • 주입 대상 필드에 @Autowired 어노테이션을 사용하여 스프링이 자동으로 해당 필드에 의존성을 주입한다.
  • 코드가 간결하고 간편하지만, 필드 주입을 사용할 때 외부에서 변경이 불가능해서 테스트가 힘들고 순환 참조 등의 문제에 노출될 수 있으므로 주의해야 한다.
  • DI 프레임워크가 없으면 아무것도 할 수 없다.
  • 사용하지 않는 것을 추천한다.

ex)

@Component
public class SpringServiceImpl implements SpringService {
    // 필드 주입
    @Autowired
    private SpringRepository springRepository; 
    
}

 

 

일반 메서드 주입 (Method Injection)

  • 일반 메서드 주입은 일반 메서드를 통해 의존성을 주입하는 방법이다.
  • 생성자 주입과 유사하게 한 번에 모든 의존성을 주입받을 수 있으며, 메서드를 호출함으로써 의존성을 주입한다.
  • 일반적으로 잘 사용하지 않는다.

 ex)

@Component
public class SpringServiceImpl implements SpringService {
    private SpringRepository springRepository;

    // 일반 메서드 주입
    @Autowired
    public void springMethod(SpringRepository springRepository) {
        this.springRepository = springRepository;
    }
}

 

 

스프링 빈의 옵션 처리

@Autowired(required=false)

@Autowired 어노테이션에 required=false를 지정하면 해당 빈이 반드시 주입되어야 하는 필수적인 의존성이 아니라는 것을 나타낸다. 즉, 해당 타입의 빈이 존재하지 않더라도 주입 에러가 발생하지 않고, 만약 주입 가능한 빈이 없다면 수정자 메서드 자체가 호출이 되지 않는다.

 

org.springframework.lang.@Nullable

@Nullable 어노테이션은 해당 매개변수, 필드, 메서드 반환값 등이 null이 될 수 있음을 나타낸다. 자동 주입 대상이 없으면 null이 입력되고, 코드 리뷰나 정적 분석 도구를 통해 null 관련 경고를 발생시킬 수 있게 한다.

 

ex)

public class SpringServiceImpl implements SpringService {
    private final SpringRepository springRepository;

    // 생성자 주입
    @Autowired(required = false)
    public SpringServiceImpl(@Nullable SpringRepository springRepository) {
        this.springRepository = springRepository;
    }
}

 

반응형

'Spring' 카테고리의 다른 글

[스프링] 롬복(Lombok)  (0) 2023.07.22
[스프링] 생성자 주입을 권장하는 이유  (0) 2023.07.22
[스프링] @Component  (0) 2023.07.18
[스프링] 싱글톤 패턴  (0) 2023.07.17
[스프링] BeanDefinition  (0) 2023.07.16

+ Recent posts