Adventure Time - Lady Rainicorn [SpringBoot] - 자바 코드로 직접 스프링 빈 등록 방법
본문 바로가기
카테고리 없음

[SpringBoot] - 자바 코드로 직접 스프링 빈 등록 방법

by 강켄트 2023. 1. 15.

☺️ 김영한님의 '스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술'을 공부하고 정리한 글입니다.

 

스프링 빈을 등록하는 2가지 방법

  • 컴포넌트 스캔과 자동 의존관계 설정 
  • 자바 코드로 직접 스프링 빈 등록 

 

자바 코드로 직접 스프링 빈 등록 방법 

- 컨트롤러에 @Controller 어노테이션만 남겨두고, 해당 스프링 어플리케이션이있는 패키지에 Config 파일을 생성한다.

- 생성한 Config 파일 클래스에 @Configuration 어노테이션을 붙인다.

- 빈으로 등록할 서비스와 레파지토리에 @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();
    }
}

 

 

🤔 자바 코드로 직접 스프링 빈 등록 방법은 어떤 상황에서 사용할까?

정형화되지 않거나, 상황에 따라 구현 클래스를 변경해야 할 경우

 

상황

아직 데이터 저장소를 선정하지 않았다.

그렇기 때문에 MemberRepository를 인터페이스로 만들고, 구현체로 MemoryMemberRepository를 설계했다.

추후 MemoryMemberRepository를 다른 다른 리포지토리로 교체 예정 

 

자바 코드로 직접 스프링 빈 등록 방법을 사용할 경우 

리포지토리를 교체할 때, 기존 코드들에 영향을 미치지 않고 교체가 가능하다. 

 

예시)

Comfig 파일에서 MemoryMemberRepository만 변경해주면 된다. 

 

 

p.s.

스프링 빈 등록 방법에 대해 배워서 알고는 있었지만, 

정확히 어떤 경우 사용하는지 알지 못하고 흔히 사람들이 많이 사용하는 대로 썼었는데

이유에 대해 알고 나니 사용하기 전에 조금 더 생각을 하면서 쓸 수 있을 것 같다.

 

댓글