Spring/스프링 입문 - 스프링 부트, 웹 MVC, DB 접근 기술

10. 자바 코드로 직접 스프링 빈 등록하기 | Spring이 @Configuration를 읽고 Spring Bean에 등록해준다.

DEV-HJ 2023. 3. 5. 19:46
반응형

전 게시물의 회원 서비스와 회원 리포지터리의 @Service, @Repository, @Autowired 어노테이션을 제거하고 진행한다.

 

SpringConfig.java 

package hello.hellospring.service;

import hello.hellospring.repository.MemberRepository;
import hello.hellospring.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(); //구현체
    }
}

SpringConfig 파일 생성하고 위 코드대로 하면 Spring이 뜰때 @Configuration를 읽고 Spring Bean에 등록해준다.


참고

DI에는 필드 주입, Setter 주입, 생성자 주입 이렇게 3가지 방법이 있다.

의존관계가 실행중에 동적으로 변하는 경우는 거의 없음으로 생성자 주입을 권장한다.

Setter 주입이나 필드 주입은 객체가 생성된 후에 의존성이 설정되기 때문에, 객체가 완전히 초기화되지 않은 상태에서 사용될 수 있다.

이는 의존성을 보장받지 못한 상태에서의 예기치 못한 동작을 초래할 수 있기 때문에 권장하지 않는다.

반면에, Setter 주입이나 필드 주입은 의존성을 변경할 수 있기 때문에, 객체의 상태가 예측하기 어려워질 수 있습니다

 

참고

실무에서는 주로 정형화된 컨트롤러, 서비스, 리포지터리 같은 코드는 컴포넌트 스캔을 사용한다.

그리고 정형화 되지 않거나, 상황에 따라 구현 클래스를 변경해야 하면 설정을 통해 스프링 빈으로 등록한다.

 

주의

@Autowired를 통한 DI는 helloController, MemberService등과 같이 스프링이 관리하는 객체에서만 동작한다.

스프링 빈으로 등록하지 않고 내가 직접 생성한 객체에서는 동작하지 않는다

반응형