[김영한 스프링 강의] 스프링 빈과 의존관계
by mini_min
[스프링 빈을 등록하고 의존관계를 설정하기]
회원 컨트롤러가 회원 서비스와 회원 리포지토리를 사용할 수 있게 의존관계를 준비한다.
MemberService 가 스프링 빈에 등록되어 있지 않다.
-> @Service 어노테이션을 붙인다.
-> 스프링 컨테이너에 등록한다.
컨트롤러와 서비스 연결 : Autowired
-> 생성자를 호출해서 연결
메모리 리포지토리 연결 : Autowired
-> 리포지토리 주입!
@Service
public class MemberService {
private final MemberRepository memberRepository;
@Autowired
public MemberService(MemberRepository memberRepository){
this.memberRepository = memberRepository;
}
@Controller
public class MemberController {
private final MemberService memberService;
//Autowired : 스프링 컨테이너에 있는 멤버 서비스를 연결 시켜준다.
@Autowired
public MemberController(MemberService memberService) {
this.memberService = memberService;
}
@Repository
public class MemoryMemberRepository implements MemberRepository{
즉, helloController -> memberService -> memberRepository
: 연결 ✨
[스프링 빈을 등록하는 방법]
1. 컴포넌트 스캔 (어노테이션으로 연결)
2. 자바 코드로 직접 스프링 빈 등록
[컴포넌트 스캔과 자동 의존관계 설정]
@Component : 스프링 빈으로 자동 등록
@Controller : 컨트롤러 등록!
@Service, @Repository 모두 자동으로 스프링 빈에 등록된다.
[참고]
스프링 빈을 등록할 때, 기본으로 싱글톤으로 등록한다. 같은 스프링 빈이면 모두 같은 인스턴스이다. 특별한 경우를 제외하면 대부분 싱글톤을 사용한다.
[스프링 빈 직접 등록]
Controller 는 두고, Service 와 Repository 를 직접 @Bean 어노테이션을 가지고 스프링 빈에 등록할 수 있다.
package hello.hellospring;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import hello.hellospring.service.MemberService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
@Bean
public MemberService memberService() {
return new MemberService(memberRepository());
}
@Bean
public MemberRepository memberRepository() {
return new MemoryMemberRepository();
}
}
* 예전에는 xml 가지고 설정을 하곤 했다.
*참고 : DI 에는 생성자 주입, 필드 주입, Setter 주입
(생성자 주입을 쓰자! ^^ 권장~)
* 실무에서는 컴포넌트 스캔을 사용한다. 정형화 되지 않거나, 상황에 따라 구현 클래스를 변경해야할 때는 설정을 통해 스프링 빈으로 등록한다.
'Spring' 카테고리의 다른 글
[김영한 스프링 강의] JDBC, JPA, AOP 개념 (0) | 2023.05.15 |
---|---|
[김영한 스프링 강의] H2 데이터베이스 설치 (0) | 2023.05.13 |
[김영한 스프링 강의] 회원 관리 예제 - 백엔드 개발 (0) | 2023.05.12 |
[김영한 스프링 강의] 스프링 웹 개발 기초 (0) | 2023.05.09 |
[김영한 스프링 강의] 프로젝트 생성 및 세팅 (0) | 2023.05.08 |
블로그의 정보
개발자 미니민의 개발로그
mini_min