자바코드로 직접 스프링 빈 등록하기
스프링 빈을 등록하는 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
애노테이션을 붙여서 작성해주면 된다.
Author And Source
이 문제에 관하여(자바코드로 직접 스프링 빈 등록하기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@olzlgur/자바코드로-직접-스프링-빈-등록하기저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)