티스토리 뷰

Spring Boot

Dependency Injection

seoca 2019. 1. 30. 14:21

 

 

DI Dependency Injection 의존성 주입

 

- IoC (Inversion of Control) and DI are used to be interchangeable. 

 

- A programmer is central to the program, but the control of the entire program is the framework. 

 

- Inject bean by assembler not Object itself

 

- Spring Container create Bean and control the life cycle of it. 

 

 

 

Example Code I

 
public class Person{
    private Writer text;
 
    public Person() {
        text = new AnotherWriter();
    }
}
 
 

 

Between Person Object and Writer Object have tight coupling. If Writer Object is changed, Person Object is affected as well. And, if it is tight coupling, It's difficult to make unit test code.

 

 

 

 

 

 

How to do Dependency Injection.

 

1. Constructor Injection 

2. Setter Injection

3. Interface Injection

 

 

 

 

 

Why do we need Dependency Injection?

 

- to get loosely coupled (Important in application programming)

 

- Reuseable code

 

- to be able to test each unit. When it's loosely coupled, you can test a certain class with a mock object without affecting other classes or database. 

 

- Less Boiler-plate code

 

 

 

 

 

 

Reference 

https://www.youtube.com/watch?v=K5bkniAjkZA

https://gmlwjd9405.github.io/2018/11/09/dependency-injection.html

https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring

 

'Spring Boot' 카테고리의 다른 글

Creating Spring Boot application with IntelliJ II  (0) 2019.02.27
Creating Spring Boot application with IntelliJ  (0) 2019.02.27
@RestController  (0) 2019.02.10
Spring Boot annotation  (0) 2019.01.26
객체주입 annotation 의 차이  (0) 2019.01.05