코딩왕랄프👊🏻

[Spring] 의존성 주입의 3가지 방식 본문

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

https://jgrammer.tistory.com/entry/springboot-%EC%9D%98%EC%A1%B4%EC%84%B1-%EC%A3%BC%EC%9E%85-%EB%B0%A9%EC%8B%9D-%EA%B2%B0%EC%A0%95

반응형
LIST

'Spring' 카테고리의 다른 글

[SpringBoot] Intellij에서 Querydsl 사용시 import 문제  (0) 2023.01.10
[Spring] 접근 제어자  (0) 2022.03.21
[JPA] GeneratedValue  (0) 2022.03.17
[JPA] @Id 어노테이션  (0) 2022.03.17
[JPA] @Builder 어노테이션  (0) 2022.03.17