본문 바로가기

공부/CS 기초이론

[JAVA / Spring] DI의 구현 방법

DI(Dependency Injection)을 구현하는 방법에는 아래의 3가지 방법이 있다.

 

1. Field Injection 

2. Setter Injection

3. Constructor Injection

 

1. Field Injection(필드 주입)

 

@Service
public class ExampleServiceImpl implements ExampleService {
    
    @Autowired
    private SampleService sampleService;
    
    @Override
    public void exampleMethod() {
    	sampleservice.sampleMethod();
    }
}

 

변수 선언부에 @Autowired 어노테이션을 붙인다.

 

2. Setter Injection

@Service
public class ExampleServiceImpl implements ExampleService {
    
    private SampleService sampleService;
    
    @Autowired
    public void setSampleService(SampleService sampleService) {
    	this.sampleService = sampleService;
    }
    
    @Override
    public void exampleMethod() {
    	sampleservice.sampleMethod();
    }
}

 

Setter 메소드에 @Autowired 어노테이션을 붙인다.

 

3. Constructor Injection

 

@Service
public class ExampleServiceImpl implements ExampleService {
    
   private final SampleService sampleService;
   
   @Autowired
   public ExampleServiceImpl(SampleService sampleService) {
   	this.sampleService = sampleService;
   }
    
    @Override
    public void exampleMethod() {
    	sampleservice.sampleMethod();
    }
}

 

생성자에 @Autowired 어노테이션을 붙여 의존성을 주입받는 방법이다.

 

 

Spring Framework 레퍼런스에서 권장하는 방법은 Constructor Injection 이다.

 

생성자를 통한 의존성 주입을 사용하는 이유는

 - 주입받을 필드를 final로 선언

 - 순환 참조 방지 (ex. A클래스가 B클래스를 참조하고, B클래스가 A클래스를 참조할때 같은 경우)

 - 필수적으로 사용해야 하는 의존성 없이는 인스턴스를 만들 수 없게 강제 할 수 있음

 - 생성자를 사용하면 객체의 의존성이 불변하므로 객체의 상태를 예측할 수 있음

 - Setter를 사용하면 객체의 의존성이 변경될 수 있음. 

 

상황에 맞는 방법을 사용하는 것이 중요하다. 

'공부 > CS 기초이론' 카테고리의 다른 글

소수점 표현시 주의점과 Java의 BigDecimal 사용  (0) 2024.02.06
[Web] REST API 규칙  (0) 2023.04.14
[Web] URI, URN, URL 구분하기  (0) 2023.04.12
[Web] REST에 대해 간단 정리  (0) 2023.04.12
[Web] HTTP Method  (0) 2023.04.11