Spring
[Spring] 의존성 주입의 3가지 방식
hyerm_2
2022. 3. 20. 19:33
반응형
SMALL
"@Autowired"란 필요한 의존 객체의 “타입"에 해당하는 빈을 찾아 주입한다.
- 생성자
- setter
- 필드
위의 3가지의 경우에 Autowired를 사용할 수 있다.
Autowired는 기본값이 true이기 때문에 의존성 주입을 할 대상을 찾지 못한다면 애플리케이션 구동에 실패한다.
의존성 주입 3가지의 방식
첫번째, Field Injection
Field Injection은 의존성을 주입하고 싶은 필드에 @Autowired 어노테이션을 붙여주면 의존성이 주입된다.
@RestController
public class PostController {
@Autowired
private PostService postService;
}
두번째, Setter based Injection
setter메서드에 @Autowired 어노테이션을 붙여 의존성을 주입하는 방식이다.
@RestController
public class PostController {
private PostService postService;
@Autowired
public void setPostService(PostService postService){
this.postService = postService;
}
}
세번쨰, Constructor based Injection
생성자를 사용하여 의존성을 주입하는 방식이다.
@RestController
public class PostController {
private final PostService postService;
public PostController(PostService postService){
this.postService = postService;
}
}
Reference
반응형
LIST