- 의존성 주입
1. Constructor(생성자)
2. Setter
3. Field
1. Constructor(생성자)
public class ExampleCase {
private final ChocolateService chocolateService;
private final DrinkService drinkService;
@Autowired
public ExampleCase(ChocolateService chocolateService, DrinkService drinkService) {
this.chocolateService = chocolateService;
this.drinkService = drinkService;
}
}
2. Setter
public class ExampleCase{
private ChocolateService chocolateService;
private DrinkService drinkService;
@Autowired
public void setChocolateService(ChocolateService chocolateService){
this.chocolateService = chocolateService;
}
@Autowired
public void setDrinkService(DrinkService drinkService){
this.drinkService = drinkService;
}
}
3. Field
public class ExampleCase{
@Autowired
private ChocolateService chocolateService;
@Autowired
private DrinkService drinkService;
}
- 생성자 주입의 단점은 위의 Constructor(생성자) 코드처럼 생성자를 만들기 번거롭다는 것이다.
- Lombok을 사용하여 간단한 방법으로 생성자 주입 장식의 코딩을 할 수 있다.
1. @RequiredArgsConstructor를 사용하지 않고 생성자 주입하는 방법
@Service
public class BannerServiceImpl implements BannerService {
private BannerRepository bannerRepository;
private CommonFileUtils commonFileUtils;
@Autowired
public BannerServiceImpl(BannerRepository bannerRepository, CommonFileUtils commonFileUtils) {
this.bannerRepository = bannerRepository;
this.commonFileUtils = commonFileUtils;
}
2. 필드 주입 방식을 사용한 Service
@Service
public class BannerServiceImpl implements BannerService {
@Autowired
private BannerRepository bannerRepository;
@Autowired
private CommonFileUtils commonFileUtils;
3. RequiredArgsConstructor를 활용한 생성자 주입
@Service
@RequiredArgsConstructor
public class BannerServiceImpl implements BannerService {
private final BannerRepository bannerRepository;
private final CommonFileUtils commonFileUtils;
728x90
'Programming > Spring' 카테고리의 다른 글
Spring - MVC 기본 동작 원리 (0) | 2023.06.05 |
---|---|
Spring - @RequestParam, @ModelAtttribute, WebDataBinder (0) | 2023.06.02 |
Spring - 스프링 MVC 구현하기(Mapper, @Valid, 등...) (0) | 2023.05.30 |
Spring - bean, root-context, servlet-context, (0) | 2023.05.29 |
Spring - 정리 (2023.05.26.FRI) (0) | 2023.05.26 |