반응형
Dependency Injection
DI (의존성 주입)은 객체 간의 결합을 느슨하게 만들기 위한 디자인 패턴이다.
Spring 프레임워크에서는 DI를 통해 객체 간의 관계를 설정한다.
주요 형태로는 세 가지가 있다.
Constructor Injection [생성자 주입]
객체를 생성할 때 생성자를 통해 의존성을 주입한다.
public class MyService {
private final MyRepository myRepository;
// 생성자 주입
public MyService(MyRepository myRepository){
this.myRepository = myRepository;
}
}
Setter Injection [Setter 주입]
Setter 메서드를 통해 의존성을 주입한다.
public class MyService{
private MyRepository MyRepository;
// Setter 주입
public void setMyRepository(MyRepository MyRepository){
this.MyRepository = MyRepository;
}
}
Method Injection [메서드 주입]
메서드를 통해 의존성을 주입한다.
public class MyService{
// 메서드 주입
public void injectDependency(MyRepository myRepository){
// 의존성 주입 로직
}
}
Spring에서는 주로 생성자 주입을 선호하며, @Autowired
어노테이션을 사용하여 의존성 주입 로직을 작성하지 않고도 의존성을 자동으로 주입할 수 있다.
@Service
public class MyService{
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository){
this.myRepository = myRepository;
}
}
반응형
'BackEnd > Spring Boot' 카테고리의 다른 글
[Spring Boot] POJO, DTO, DAO, VO, Entity (0) | 2023.12.30 |
---|---|
[Spring Boot] Java Bean (1) | 2023.12.27 |