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

gotcha!!·2023년 8월 10일
0

SpringBoot

목록 보기
3/7

자바 코드로 직접 빈 등록

주로 정형화된 컨트롤러, 서비스, 레파지토리 같은 코드는 컴포넌트 스캔을 사용
그리고 정형화 되지 않거나, 상황에 따라 구현 클래스를 변경해야하면 자바 코드로 스프링 빈을
등록한다.

먼저 SpringConfig라는 클래스를 만든다.
그리고 아래와 같이 @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();
    }

}
profile
ha lee :)

1개의 댓글

comment-user-thumbnail
2023년 8월 10일

이런 유용한 정보를 나눠주셔서 감사합니다.

답글 달기