Programming/Spring

Spring - @RequiredArgsConstructor

잇(IT) 2023. 5. 31. 20:43

- 의존성 주입

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;

 

 

 

- 출처 : https://velog.io/@developerjun0615/Spring-RequiredArgsConstructor-%EC%96%B4%EB%85%B8%ED%85%8C%EC%9D%B4%EC%85%98%EC%9D%84-%EC%82%AC%EC%9A%A9%ED%95%9C-%EC%83%9D%EC%84%B1%EC%9E%90-%EC%A3%BC%EC%9E%85

728x90