Coding/Spring(Boot)

[Spring]자바 코드로 직접 spring bean 등록

민톨이 2024. 6. 11. 00:14
728x90

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

 

컴포넌트 스캔 방법 말고도 스프링 빈을 등록하는 방법으로는 자바 코드로 직접 등록할 수 있다.

- 주로 정형화 되지 않았거나 상황에 따라 구현 클래스를 변경해야 하는 경우 설정을 통해 스프링 빈으로 등록

 

=> 기존에 컴포넌트 스캔 방법으로 썼던 @Service, @Repository ,,,,등 애노테이션을 제거하고 진행해야 함

 

 

//SpringConfig.java

package hello.hello_spring.service;

import hello.hello_spring.repository.MemberRepository;
import hello.hello_spring.repository.MemoryMemberRepository;
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();
    }
}

 

@Configuration을 생성하고

그 밑에 @Bean 애노테이션 + 메서드에 반환값을 적어준다.

 

이 방식은 기존에 운영중인 코드에 손대지 않고 구현체를 변경하는 방법으로 쓸 수도 있다. (상황에 따른 구현체 변경)