본문 바로가기
개발 공부

[@Autowired vs @RequiredArgsConstructor] feat. 의존성 주입

by 도됐좋 2023. 8. 22.
순서
1. 의존성 주입이란
2. @Autowired란
3. @RequiredArgsConstructor이란

 

✅ 의존성 주입

- 객체 간의 의존 관계를 외부에서 설정해주는 것

- 의존성 주입을 이해하려면 기본적인 스프링 동작 과정을 보는게 편함

  (https://for-your-information.tistory.com/4)

 

➤ 의존성 주입 3가지 방법

1. 생성자 주입(가장 권장되는 방법)

- 객체가 생성될 때 딱 한 번 호출되는 것이 보장됨

- 의존 관계에 있는 객체들을 final로 선언 가능함

- 생성자가 하나일 경우 @Autowired 생략 가능

@Controller
public class TestController {

    private final TestService testService;
    
    //@Autowired
    public TestController(TestService testService) {
    	this.testService = testService;
    }
}

 

 

 

2. 필드 주입

- 필드에 @Autowired 어노테이션만 붙이면 되는 가장 간단한 방법

-  외부에서 변경하기 힘들고, 프레임워크에 의존적이고, 객체지향적이지 않은 등 많은 단점이 있어서 사용 '지양'

@Controller
public class TestController {
    @Autowired
    private TestService testService;
}

 

3. 수정자 주입

- setter를 생성하고 그 위에 @Autowired 작성

- 선택적이고 변화 가능한 의존 관계에 사용

@Controller
public class TestController {

    private TestService testService;
    
    @Autowired
    public void setTestService(TestService testService) {
        this.testService = testService;
    }
}

 


 @Autowired

- 필드 주입 방식의 의존성 관리 방법

- Field, Setter 메소드, 생성자에 사용 가능

 

단점

-  단일 책임의 원칙 위반 가능성

- 코드 변이 가능성

- 불확실한 참조

- 순환 참조 가능성


 @RequiredArgConstructor

- 생성자로 의존성 주입 해줌

- final 키워드가 붙은 필드에 대해 생성자를 만들어 줌

- @RequiredArgsConstructor 사용한 경우

@Service
@RequiredArgsConstructor
public class TestServiceImpl implements TestService {

     private final TestRepository testRepository;

}

- @RequiredArgsConstructor 사용하지 않은 경우

@Service
public class TestServiceImpl implements TestService {

    private final TestRepository testRepository;
    
    @Autowired
    public TestServiceImpl(TestRepository testRepository) {
         this.testRepository = testRepository;
    }
    
}

 장

- 코드 변이에 대한 안전성

- 순환 참조에 대한 안정성