스프링 의존성 주입 방식

2019. 7. 22. 10:22Spring

 

 

프로젝트를 진행하던 중 

멘토님께서 요즘 스프링에서는 의존성을 주입할 때 

@Autowired 를 사용하는 대신 final, 생성자 주입 방식을 추천한다고 말하셨다.

스프링 사용 경력이 한 번 밖에 안되는 나는 @Autowired 밖에 알지 못했고, 더 나은 코드를 위해 오늘도 역시나 공부를 한다. 

 


의존성 주입 방법

1. field injection

@Autowired를 사용한 방식 

 @Service
    public class SampleService {
    	@Autowired
        private  SampleRepository sampleRepository;
        
    }

 

2. Constructor injection

 @Service
    public class SampleService {
        private final SampleRepository sampleRepository;

        public SampleService(SampleRepository sampleRepository) {
            this.sampleRepository = sampleRepository;
        }
    }

 

@Autowired는 사용하지 않는다.

 

3.Setter injection

 @Service
    public class SampleService {
        private SampleRepository sampleRepository;

    	@Autowired
    	public void setSampleRepository(SampleRepository sampleRepository){
        	this.sampleRepository = sampleRepository;
    	}
    }

 

4.bean tag

Spring MVC에서 root-context.xml에 bean태그를 이용하여 주입하는 방식.

 

 

 

 

- Lombok 어노테이션을 사용하여 Constructor injection을 할 경우

@RequiredArgsConstructor : 필수 인자를 가진 생성자 생성.  final 필드를 매개 변수로 취하는 생성자 생성

@NonNull : null인지 확인. null인 경우 NullPointerException 발생.

 

field injection보다 Constructor injection을 더 권장하는 이유

- 단일책임원칙의 위반

- 테스트 기능성

DI 컨테이너에 대한 의존성을 낮춰 DI 컨테이너 없이도 단위테스트에서 인스터스화를 가능하게 한다. POJO

- final을 이용한 불변성

 

 

하단의 mimul님과 zobra님이 설명을 잘해두셨으니 매우 참고하즈앙 !

 

참고

http://www.mimul.com/pebble/default/2018/03/30/1522386129211.html

 

DI(의존성 주입)가 필요한 이유와 Spring에서 Field Injection보다 Constructor Injection이 권장되는 이유 - Mimul's Developer World

왜 DI(의존성 주입)가 필요한가? 왜 DI(의존성 주입)가 필요한가?에 대한 좋은 해답으로 Google Guice Motivation페이지에서 잘 설명해 주어서 인용해 본다. 동기요인 관련된 모든 객체들을 밀결합하는 것은 어플리케이션 개발 부분에서 짜증나는 일이 된다. 어플리케이션에는 서비스, ​​데이터, 그리고 프리젠테이션 클래스들을 연결하는 방법에는 여러 가지가 있다. 이러한 접근 방법을 비교하기 위해 피자 주문에 관련된 빌링 코드를 작성할 것이다.

www.mimul.com

https://zorba91.tistory.com/238

 

[Spring]필드 주입(Field Injection) 대신 생성자 주입(Constructor Injection)을 사용해야 하는 이유

Field Injection is not recommended.md Field Injection을 추천하지 않는 이유(+Constructor Injection을 추천하는 이유) 의존성 주입을 할 때 Field Injection은 좋지 않다는 글을 읽고 왜 그런지 찾아봤다. 스..

zorba91.tistory.com