본문 바로가기
반응형
Spring/Spring(eng)

What is DI(Dependency Injection), Why & How to use

by brightGarden02 2022. 12. 9.

What DI(Dependency Injection):

DI(Dependency Injection) is a core programming model supported by Spring Framework.

Dependency is that one object uses another object. (depends on = uses)

 

For example, if a QuestionController object uses a QuestionService object,

The QuestionController object depends on the QuestionService object.

public class QuestionController {

    private QuestionService questionService;

 

It is Dependency Injection that creating a relationship between two object.

Instead of creating an object directly, an object is created externally and then injected.

There are many different types of dependency injection.

Constructor injection, modifier injection. field injection, etc.

Spring recommends constructor injection.

 

 

 

Why use DI(Dependency Injection):

To reduce coupling and implement with flexible code by setting the relationship

between objects at the time of application execution.

 

 

 

How to use DI(Dependency Injection):

Among the DI methods, I will user constructor injection.

 

1. Write final on field object.

2. Write @RequiredArgsConstructor, the lombok feature

@Controller
@RequiredArgsConstructor
@RequestMapping("question")
public class QuestionController {

    private final QuestionService questionService;

 

 

@RequiredArgsConstructor is an interface supported by Lombok.

It creates a constructor instead.

댓글


반응형
반응형