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

2023. 6. 12. 23:08·노빠꾸 개발일지/SPRING
반응형

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

 

의존관계 주입 방법

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.

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

반응형
저작자표시 비영리 변경금지 (새창열림)

'노빠꾸 개발일지 > SPRING' 카테고리의 다른 글

[Spring Data JPA] 쿼리 메소드(Query Method) 방식 알아보기  (0) 2023.06.14
[Spring Boot] 스프링부트 H2 DB 연결해보기  (0) 2023.06.13
스프링 프레임워크(Spring Framework)와 스프링 부트(Spring Boot)  (0) 2023.06.03
Spring Security 5.7.x 이후 버전에서 WebSecurityConfigurerAdapter 클래스의 deprecation 이유와 대안 방법  (0) 2023.02.26
스프링부트 프로젝트 기본 생성 방법 및 간단한 정리  (0) 2023.02.19
'노빠꾸 개발일지/SPRING' 카테고리의 다른 글
  • [Spring Data JPA] 쿼리 메소드(Query Method) 방식 알아보기
  • [Spring Boot] 스프링부트 H2 DB 연결해보기
  • 스프링 프레임워크(Spring Framework)와 스프링 부트(Spring Boot)
  • Spring Security 5.7.x 이후 버전에서 WebSecurityConfigurerAdapter 클래스의 deprecation 이유와 대안 방법
No Backing
No Backing
노빠꾸
    300x250
  • No Backing
    누릇한 노빠꾸 블로그
    No Backing
  • 전체
    오늘
    어제
    • 분류 전체보기 (144)
      • 노빠꾸 서버 (20)
        • AWS (0)
        • 설치관련 (7)
        • 명령어 정리 (2)
        • 서버 설정 (8)
        • Nginx (2)
      • 노빠꾸 개발일지 (70)
        • JAVA (16)
        • JQUERY & JAVASCRIPT (10)
        • HTML5 (0)
        • SPRING (16)
        • Design Patterns (1)
        • DAUM API (1)
        • GIT (10)
        • Python (1)
        • SPRING SECURITY (1)
        • Vue (3)
      • 노빠꾸 데이터베이스 (9)
        • SQL (1)
        • ORACLE (3)
        • MySql (5)
      • 노빠꾸 일상 (13)
      • 노빠꾸 책 추천 (4)
      • 노빠꾸 경제 (20)
      • 노빠꾸 맥북 사용기 (7)
      • 노빠꾸 정보처리기사 정리 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    WebSecurityConfigurerAdapter Deprecated
    스프링부트
    인텔리제이
    MySQL 사용자 계정 생성
    JPA 쿼리 메소드
    websecurityconfigureradapter 사용법
    맥북 사용 팁
    스프링 시큐리티 5.7 버전이후 변경사항
    websecurityconfigureradapter란
    Linode
    주식용어
    우분투 자바 설치
    사이트맵
    맥북 단축키
    websecurityconfigureradapter 빈 등록
    MySQL 데이터베이스 생성
    깃허브 코파일럿
    스프링부트 프로젝트
    금융용어
    스프링부트란
    Spring boot
    리노드
    티스토리 사이트맵 등록
    리눅스 자바 설치
    경제용어
    개인서버 추천
    WebSecurityConfigurerAdapter
    스프링시큐리티 websecurityconfigureradapter
    websecurityconfigureradapter 변경사항
    스프링부트 JPA
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
No Backing
[스프링] 의존성 주입(Dependency Injection) 방법
상단으로

티스토리툴바