Spring

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

Bepoz 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;
    }
cs

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

더불어서

1
2
3
4
5
@RequiredArgsConstructor
public class EventController {
 
    private final EventRepository eventRepository;
 
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();
    }
}
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;
    }
cs

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

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