자바 코드로 직접 스프링 빈 등록하기
상황 발생 : 정해지지 않은 DB
해결 방법 : SpringConfig로 빈을 직접 등록, DB가 선택됬을때 SpringConfig의 MemoryMemberRepository만 수정하면된다.
SpringConfig 생성
main > java > hello.hellospring > SpringConfig.java 생성
package hello.hellospring;
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(memoryMemberRepository());
}
@Bean
public MemoryMemberRepository memoryMemberRepository() { // 차후에 MySqlDBMemberRepository 처럼 해당하는 인터페이스 구현체를 통해 변경해준다.
return new MemoryMemberRepository();
}
}
결론
자바에서 SpringConfig를 통해서 빈을 직접 등록을 해야 될때는
1) 아직 정해지지 않은 DB 처럼 인터페이스의 구현체를 계속 변경해야될 상황에 사용하면 용이하다.
이 글은 인프런의
제목 : 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
강사 : 김영한 님의 동영상을 참조해 만들었습니다.
'Spring > 스프링 입문' 카테고리의 다른 글
h2 데이터베이스 설치 및 연동 (0) | 2022.03.08 |
---|---|
회원 웹 기능 - 등록, 출력 (0) | 2022.03.08 |
컴포넌트 스캔과 자동 의존관계 설정 (0) | 2022.03.07 |
회원 관리 예제 - 백엔드 개발 (2) (0) | 2022.03.07 |
회원 관리 예제 - 백엔드 개발 (1) (0) | 2022.03.07 |