on
예제로 배우는 스프링 프레임워크 입문 - Spring Bean
예제로 배우는 스프링 프레임워크 입문 - Spring Bean
빈 (Bean)
스프링 IoC 컨테이너가 관리하는 객체
// applicationContext의 개입 없이 만들어 졌으므로 아래 객체는 Bean이 아니다. OwnerController ownerController = new OwnerController(); OwnerController bean = applicationContext.getBean(OwnerController.class); // applicationContext가 관리하므로 위 객체는 Bean이다.
어떻게 등록하지?
Component Scanning @Component @Repository @Service @Controller Configuration
@Controller annotation에는 @Component annotation이라는
meta annotaion을 사용하는 annotation이다. 사실상 @Component annotation이라고 할 수 있따.
annotation processor중에 IOC Conationer가 사용하는 여러가지 Interface가 있는데
그런 Interface들을 LifeCycle callback이라 부른다.
이 LifeCycle callback중에 @Component annotation을 찾아서 그 class의 instance를 만들어 Bean으로 등록하는
일을 하는 annotation processor인 @Component Scan 등록되어 있다.
@SpringBootApplication -> ComponentScan { @org.springframework.core.annotation.AliasFor("basePackages") java.lang.String[] value() default {}; @org.springframework.core.annotation.AliasFor("value") java.lang.String[] basePackages() default {}; java.lang.Class[] basePackageClasses() default {}; java.lang.Class nameGenerator() default org.springframework.beans.factory.support.BeanNameGenerator.class; java.lang.Class scopeResolver() default org.springframework.context.annotation.AnnotationScopeMetadataResolver.class; org.springframework.context.annotation.ScopedProxyMode scopedProxy() default org.springframework.context.annotation.ScopedProxyMode.DEFAULT; java.lang.String resourcePattern() default "**/*.class"; boolean useDefaultFilters() default true; org.springframework.context.annotation.ComponentScan.Filter[] includeFilters() default {}; org.springframework.context.annotation.ComponentScan.Filter[] excludeFilters() default {}; boolean lazyInit() default false; @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @java.lang.annotation.Target({}) }
@ComponentScan은 해당 annotation이 붙어있는 하위 패키지의 모든 클래스들을 훑어보며 @Component annotation을 포함하는 annotation들을 찾아 Bean으로 등록한다.
(@Repository, @Service, @Controller, @Configuration 등등 // 직접 만들 수 도 있다.)
@Repository는 Spring Data JPA가 제공해주는 기능에 의해 Bean으로 등록이 된다.
이 경우는 특정한 Annotation이 없더라도 특정한 Interface를 상속받은 경우에
Interface를 상속받고 있는 Class를 찾아(사실상 Interface) 구현체를 내부적으로 만들어 Bean으로 등록해줌
또는 직접 일일히 XML이나 자바 설정 파일에 등록
package org.springframework.samples.petclinic.Sample; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration //-> IOC Container -> Component Scan public class SampleConfig { @Bean //-> Bean등록 public SampleController sampleController() { return new SampleController(); } }
어떻게 꺼내쓰지?
@Autowired 또는 @Inject
또는 ApplicationContext에서 getBean()으로 직접 꺼내거나
특징
오로지 “빈"들만 의존성 주입을 해줍니다.
https://github.com/devjun63/spring-petclinic/commit/eeac4454a38f6309824d6fdcccf7e321c34cd7cb
from http://devjun.tistory.com/235 by ccl(A) rewrite - 2021-11-26 01:01:36