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

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

  • 컴포넌트 스캔을 통한 스프링 빈 등록
  • 자바 코드를 통한 스프링 빈 등록

스프링 빈을 등록하는 2가지 방법 중 두 번째 방법을 통해 스프링 빈을 등록하려고 한다.

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

자바 코드로 스프링 빈을 등록할 때에는 @Service @Repository @Autowired 애노테이션을 사용하지 않고 파일을 추가로 작성해주면 되는데 컨트롤러는 예외로 @Controller을 사용해야 한다.

package hello.hellospring;

import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {
}

먼저 SpringConfig라는 자바 클래스를 생성해주고 @Configuration 애노테이션을 붙여준다.

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();
    }
}

생성된 SpringConfig 클래스에 스프링 빈으로 주입하고싶은 클래스들을 작성해주면 되는데 이때 @Bean 애노테이션을 붙여서 작성해주면 된다.

좋은 웹페이지 즐겨찾기