본문 바로가기
Framekwork/SPRING

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

by 아이엠제니 2023. 2. 21.

 

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

  • 회원 서비스와 회원 리포지토리의 @Service, @Repository, @Autowired 애테이션을 제거하고 진행한다.
  • 위 애노테이션 제거 시 정상 작동 안 됨

 

💾 main > java > hello > hellospring > SpringConfig

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 읽고,
* @Bean을 스프링 빈에 등록하는 거라고 인식함
* */

@Configuration
public class SpringConfig {

    @Bean // 스프링 빈을 등록할 거임
    public MemberService memberService() {
        return new MemberService(memberRepository());
    }

    @Bean
    public MemberRepository memberRepository() {
        return new MemoryMemberRepository();
    }
}

* 여기서는 향후 메모리 리포지토리를 다른 리포지토리로 변경할 예정이므로, 컴포너느 스캔 방식 대신에 자바 코드로 스프링 빈을 설정하였다.

 

  • 참고: XML로 설정하는 방식도 있지만 최근에는 잘 사용하지 않으므로 생략함
  • 참고: DI에는 필드 주입, setter 주입, 생성자 주입 일허게 3가지 방법이 있다. 의존관계가 실행중에 동적으로 변하는 경우는 거의 없으므로 생성자 주입을 권장함
  • 참고: 실무에서는 주로 정형화된 컨트롤러, 서비스, 리포지토리 같은 코드는 컴포넌트 스캔을 사용한다, 그리고 정형화되지 않거나, 상황에 따라 구현 클래스를 변경해야 하면 설정을 통해 스프링 빈으로 등록함
  • 주의: `@Autowired`를 통한 DI는 `helloController`, `MemberService` 등과 같이 스프링이 관리하는 객체에서만 동작한다. 스프링 빈으로 등록하지 않고 내가 직접 생성한 객체에서는 동작하지 않는다.

 


스프링 빈 등록 이미지

스프링 컨테이너

helloController -> memberService -> memberRepository

 

 

 

[스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술] 강의 기록
300x250