본문 바로가기
Spring

[Spring] DI 방법과 생성자 주입을 사용해야 하는 이유

by Apère 2023. 2. 15.
반응형

Spring에서 DI 주입방법은 대표적으로 아래 3가지 방법이 있습니다 

 

1. 필드주입

@RestController
@RequestMapping("/test")
public class TestController {
    
    @Autowired
    private TestService testService;

    public int sum(int a, int b) throws Exception {
        return testService.sum(a, b);
    }
}

필드 주입은 코드가 간결해진다는 장점이 있습니다. 하지만 객체 수정이 불가능해서 요즘처럼 테스트 코드의 중요성이 강조되는 추세에 밀려 사용을 지양하게 되었습니다.

 

 

2. Setter 주입

@RestController
@RequestMapping("/test")
public class TestController {


    private TestService testService;

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

    public int sum(int a, int b) throws Exception {
        return testService.sum(a, b);
    }
}

Setter 주입을 추천하지 않는이유는 객체의 변경가능성이 있어 개발자의 실수로 불변성을 보장받지 못하기 때문입니다. 같은 이유로 DTO에서도 Setter를 지양하는 추세입니다.

 

3. 생성자 주입

@RestController
@RequestMapping("/test")
public class TestController {
    
    private final TestService testService;

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

    public int sum(int a, int b) throws Exception {
        return testService.sum(a, b);
    }
}

스프링 4.3버전 이후로는 생성자가 한개만 있을경우 @Autowired를 생략할수 있습니다. 그래서 아래와 같이 Lombok을 이용하여 더 간략한 코드로 변경가능합니다

@RestController
@RequiredArgsConstructor
@RequestMapping("/test")
public class TestController {

    private final TestService testService;

    public int sum(int a, int b) throws Exception {
        return testService.sum(a, b);
    }
}

 

Spring에서 DI를 할때 생성자 주입을 추천하는 이유는 아래와 같습니다

 

- 객체의 불변성 확보

- 순환참조 에러방지

- 테스트 코드 작성의 편리성

 

 

 

 

 

 

 

 

 

반응형

댓글