[Spring] 스프링 입문4 - Bean 등록법
com.example.intro.controller MemberController
package com.example.intro.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.example.intro.service.MemberService;
@Controller
public class MemberController {
private final MemberService ms;
@Autowired // 구동시 @service로 구동된 MemberService를 가져와 넣어준다
public MemberController(MemberService ms) {
this.ms = ms;
}
}
지금까지 우리가 개발한 서비스는 아래와 같은 순서로 연결된다.
서버에 요청이 들어왔을때, 먼저 Spring 컨트롤러에서 등록된 Bean 객체를 @Autowired로 연결하게 되는데...
Bean객체는 서버부트시 두가지 방법으로 등록될 수 있다.
1. AutoScan - @Component
각각의 컴포넌트마다 @component (@Service , @Repository ..) 등의 어노테이션을 명시하므로써
Spring 구동시 @component 가 자동스캔되므로 Bean을 자동생성 등록되는 방법
2. 수동설정 - @Configuration , @Bean
기존 소스코드에서 @component (@Service , @Repository ..) 컴포넌트라고 명시했던 어노테이션을 제거하고
연결정보를 관리할 SpringConfig.java 파일을 생성후 해당 소스에 @configuration 을 이용해
수동으로 Bean객체를 생성하라고 명령 할 수 있다.
package com.example.intro.service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.intro.repository.MemberRepository;
import com.example.intro.repository.MemoryMemberRepository;
@Configuration
public class SpringConfig {
@Bean
public MemberService memberService() {
return new MemberService(memberRepository());
}
@Bean
public MemberRepository memberRepository() {
return new MemoryMemberRepository();
}
}
기존 소스코드에서 @component (@Service , @Repository ..) 를 명시하던 어노테이션을 제거해주어야 한다.
이와같이 작성해주므로 수동으로 Bean객체를 생성해줄 수 있다.
보통 이 방법을 선호하지 않지만, 개발자가 직접 제어불가능한 외부라이브러리 등을 Bean으로 만들때
이 방법을 사용한다.
소스코드
https://github.com/bangbangu4/Spring-intro
GitHub - bangbangu4/Spring-intro: Spring-Introduction (김영한) 강의 정리
Spring-Introduction (김영한) 강의 정리. Contribute to bangbangu4/Spring-intro development by creating an account on GitHub.
github.com