ENAN

Developer, Artist, Traveler

공부/Spring

Kotlin Spring에서의 @Autowired annotation

ENAN 2021. 1. 7. 01:17

1. @autowired란?

- 필요한 의존 객체의 타입에 해당하는 빈을 찾아 주입해 주는 어노테이션.

2. java에서 사용하는 방법

@RestController
@RequestMapping("/auth")
public class AuthController{

    @Autowired
    private AuthService authService;

3. kotlin에서 사용하는 방법

  lateinit 키워드를 사용해 초기화를 미루는 것으로 간단하게 사용할 수 있다. (field injection 방식의 경우)

@RestController
@RequestMapping("/auth")
class AuthController() {

    @Autowired
    private lateinit var authService: AuthService

원래는 여기까지만 적으려고 했으나, 의존성 주입 방식에는 위에서 설명한 field Injection 외에도 setter Injection, constructor Injection 이렇게 3가지 방식이 있는데, 그중 constructor, 즉 생성자 주입 방식을 권장하는 것 같아서 더 알아보았다.

@RestController
@RequestMapping("/auth")
class AuthController(private val authService: AuthService) {

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

생성자 주입 방식의 장점으로는,

   - 테스트 시 생성자를 통해 의존성을 주입하기 용이함

   - 순환 참조가 발생하거나 빈이 제대로 주입되지 않았을 때, 컴파일 시점에서 알 수 있음

   - 생성자가 하나일 경우 autowired 생략 가능 (spring 4.3 이후로)

등이 있다. 이러한 이유로 생성자 주입 방식을 권장한다고 하니 가급적 위와 같은 방식으로 사용해 보자!