[Spring] Spring Bean이란?

SSOYEONG·2022년 3월 24일
0

스프링 입문

목록 보기
3/4
post-thumbnail

Spring Bean이란?

  • Spring IoC 컨테이너가 관리하는 자바 객체를 Bean이라고 한다.
  • 직접 new를 이용하여 생성한 객체가 아니라, Spring에 의하여 생성되고 관리되는 객체이다.
  • ApplicationContext.getBean()과 같은 메소드를 사용하여 Spring에서 직접 자바 객체를 얻어서 사용한다.

    OwnerController ownerController = new OwncerContraoller();
    -> Bean 객체 X
    OwnerController bean = applicationContext.getBean(OwnerController.class);
    -> Bean 객체 O

Spring IOC Container에 Bean을 만드는 법

방법 1. Component Scanning

  • @ComponentScan annotation은 또다른 annotation이 달린 class를 찾기 위해 어느 지점부터 살펴보아야 하는지 알려준다.
  • @Component, @Controller, @Service, @Repository 등 모두 찾아 Bean으로 등록해 주는 것이 Component Scanning이다.
  • 위 예제에서 직접 OwnerController를 빈으로 등록하지 않더라도 Spring이 알아서 IOC Container가 만들어질 때, 스캔해서 annotations를 보고 자동으로 bean으로 등록해준다.

@Controller
public class HelloController {
	@GetMapping("hello")
    public String hello(Model model){
    	model.addAttribute("data", "hello!");
        return "hello";
}

방법 2. Bean Configuration File에 직접 등록

  • @Configuration을 사용하여 Spring 프로젝트에서 Configuration 역할을 하는 class를 지정할 수 있다.
  • 해당 파일 하위에 @Bean을 사용하여 등록하고자 하는 class를 bean으로 등록한다.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
	@Bean
    public MemberService memberService(){
    	return new MemberService(memberRepository);
    }
}

References

profile
Übermensch

0개의 댓글