노빠꾸 개발일지/SPRING

[스프링] 의존성 주입(Dependency Injection) 방법

No Backing 2023. 6. 12. 23:08
반응형

스프링 의존성 주입 방법에 대해 간단히 정리해보겠습니다.

 

의존관계 주입 방법

1. 생성자 주입

생성자를 통해 의존관계를 주입받는 방법.

 

@RestController
public class UserController {

    private UserService userService;

	
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
}

이떄 생성자가 1개일 경우 @Autowired는 생략 가능하다.

 

Lombok 에노테이션을 이용한 생성자 주입 방식

@RequiredArgsConstructor : final이 붙거나 @NotNull이 붙은 필드의 생성자를 자동 생성해주는 Lombok 에노테이션

@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

}

Lombok에노테이션의 @RequiredArgsConstructor를 이용하여 생성자 코드를 자동으로 생성해 주기 때문에 생성자코드를 추가하지 않고 의존관계 주입을 받을 수 있다.

 

2. 필드주입

@Autowired 에노테이션을 통한 필드 주입 방법, @Autowired 에노테이션만 붙여주면 되기 때문에 사용이 쉽고 편리하다.

@RestController
public class UserController {

    @Autowired
    private UserService userService;
    
}

 

 

참고

 

The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not 
null
. Furthermore, constructor-injected components are always returned to the client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.

스프링 프레임워크는 생성자 주입방식을 사용하기를 권장한다.

반응형