Bepoz
파즈의 공부 일기
Bepoz
전체 방문자
오늘
어제
  • 분류 전체보기 (232)
    • 공부 기록들 (85)
      • 우테코 (17)
    • Spring (85)
    • Java (43)
    • Infra (17)
    • 책 정리 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Bepoz

파즈의 공부 일기

Spring

[Spring] @Autowired 생성자 주입방법에 대해서

2020. 9. 18. 16:12

생성자 방식으로 @Autowired를 진행할 때에 생성자가 1개이면 @Autowired 를 생략할 수 있다고 배웠다.

 

 

1
2
3
4
5
6
7
8
public class EventController {
 
    private final EventRepository eventRepository;
 
    @Autowired
    public EventController(EventRepository eventRepository) {
        this.eventRepository = eventRepository;
    }
Colored by Color Scripter
cs

위의 코드에서 @Autowired 를 생략할 수 있다는 말이다.

더불어서

1
2
3
4
5
@RequiredArgsConstructor
public class EventController {
 
    private final EventRepository eventRepository;
 
Colored by Color Scripter
cs

final 이 붙은 것들의 생성자를 만들어주는 @RequiredArgsConstructor를 이용하면 다음과 같이 더 생략해줄 수가 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
@SpringBootApplication
public class RestapiApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(RestapiApplication.class, args);
    }
 
    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
}
Colored by Color Scripter
cs

다음과 같이 파라미터가 빈으로 이미 등록이 되어있으면

1
2
3
4
5
6
7
8
9
public class EventController {
 
    private final EventRepository eventRepository;
    private final ModelMapper modelMapper;
 
    public EventController(EventRepository eventRepository, ModelMapper modelMapper) {
        this.eventRepository = eventRepository;
        this.modelMapper = modelMapper;
    }
Colored by Color Scripter
cs

다음과 같이 @Autowired를 생략한 생성자를 선언해도 된다.

물론 이 상황에서도 마찬가지로 @RequiredArgsConstructor를 이용해서 더 생략할 수가 있다.

'Spring' 카테고리의 다른 글

[Spring] EventResource를 이용한 HATEOAS 적용  (0) 2020.09.21
[Spring] Errors Serializer 만들기  (0) 2020.09.18
[Spring] ResponseEntity에 대해서  (0) 2020.09.18
[Spring] @JsonFilter 를 이용한 필드값 필터링하기  (0) 2020.09.16
[Spring] @Valid 를 이용한 Exception처리와 ThymeLeaf 처리  (0) 2020.09.15
    'Spring' 카테고리의 다른 글
    • [Spring] EventResource를 이용한 HATEOAS 적용
    • [Spring] Errors Serializer 만들기
    • [Spring] ResponseEntity에 대해서
    • [Spring] @JsonFilter 를 이용한 필드값 필터링하기
    Bepoz
    Bepoz
    https://github.com/Be-poz/TIL

    티스토리툴바