IoC container
The IoC container
IOC(Inversion of control)
스프링 framework의 IOC container의 기본패키지
org.springframework.beans
org.springframework.context
모든 유형의 object를 관리할 수 있는 구성메커니즘
BeanFactory의 sub-interface이며
AOP, Internationalization, event publication, application-layer를 제공한다.
XML, Java annotations, java coding
ClassPathXmlApplicationContext, FileSystemXmlApplicationContext
7.2.1 Configuration metadata
XML
Annotation-based configuration : 2.5
Java-based configuration : 3.0
@Configuration, @Bean, @Import and @DependsOn annotations
The id attribute is a string that you use to identify the individual bean definition
The class attribute defines the type of the bean and uses the fully qualified classname.
7.2.2 Instantiating a container
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
(services.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- services -->
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for services go here -->
</beans>
daos.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountDao"
class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for data access objects go here -->
</beans>
The property name element refers to the name of the JavaBean property, and the ref element refers to the name of another bean definition.
Composing XML-based configuration metadata
7.2.3 Using the container
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();
Bean
Bean Spring container가 관리하는 Object를 Bean이라 한다.
Bean 메타정보: bean을 어떻게 만들고 어떻게 동작하게 할것인가?의 정보
> BeanDefinition : bean instance를 기술하는 것.
Property values, construct argument values,
빈아이디, 이름, 별칭
클래스, 클래스이름
스코프,
프라퍼티 값 혹은 참조
생성자 파라미터 혹은 참조
AnnotationConfigApplicationContext
AnnotationConfigApplicationContext 는 ApplicationContext의 구현체이다
private final AnnotatedBeanDefinitionReader reader; private final ClassPathBeanDefinitionScanner scanner;
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) { this(); register(annotatedClasses); refresh(); } |
AnnotatedBeanDefinitoinReader
public void registerBean(Class<?> annotatedClass, String name, @SuppressWarnings("unchecked") Class<? extends Annotation>... qualifiers) {
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass); if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) { return; }
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd); abd.setScope(scopeMetadata.getScopeName()); String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); AnnotationConfigUtils.processCommonDefinitionAnnotations(abd); if (qualifiers != null) { for (Class<? extends Annotation> qualifier : qualifiers) { if (Primary.class == qualifier) { abd.setPrimary(true); } else if (Lazy.class == qualifier) { abd.setLazyInit(true); } else { abd.addQualifier(new AutowireCandidateQualifier(qualifier)); } } }
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName); definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); }
|
· AnnotatedGenericBeanDefinition : BeanDefinition 구현체중 하나, BeanConfig를 통해 등록될 Bean에 메타데이터를 정의한 클래스라고 할 수 있다.
· ScopeMetadata : 이름에서 알 수 있듯이 Bean Scope에 메타데이터를 정의한 클래스다.
· BeanDefinitionHolder : 이 클래스는 BeanDefinition과 name, alias를 정보를 가진는 클래스이다.
· BeanDefinitionReaderUtils : Bean을 IoC Container 즉, ApplicationContext에 저장하는 역할을 하는 utils 클래스 이다.
· BeanDefintionRegistry : Bean Definition을 register하는 유일한 인터페이스이다.
일반적으로 BeanFactory에서 구현된다( DefaultListableBeanFactory와 GenericApplicationContext)
·
BeanFactory
Spring bean container에 접근하기 위한 최상위 interface이다.
핵심은 Application의 component들을 이 인터페이스로 중앙집중식 등록(registry) 및 설정(configuration)하는 것이다.
BeanFactory는 bean definition을 로드하고 org.springframework.beans 패키지를 사용하여 bean을 설정한다.
Initializations methods and ordering 1. BeanNameAware's setBeanName 2. BeanClassLoaderAware's setBeanClassLoader 3. BeanFactoryAware's setBeanFactory 4. EnvironmentAware's setEnvironment 5. EmbeddedValueResolverAware's setEmbeddedValueResolver 6. ResourceLoaderAware's setResourceLoader (only applicable when running in an application context) 7. ApplicationEventPublisherAware's setApplicationEventPublisher (only applicable when running in an application context) 8. MessageSourceAware's setMessageSource (only applicable when running in an application context) 9. ApplicationContextAware's setApplicationContext (only applicable when running in an application context) 10. ServletContextAware's setServletContext (only applicable when running in a web application context) 11. postProcessBeforeInitialization methods of BeanPostProcessors 12. InitializingBean's afterPropertiesSet 13. a custom init-method definition 14. postProcessAfterInitialization methods of BeanPostProcessors
|
1. postProcessBeforeDestruction methods of DestructionAwareBeanPostProcessors 2. DisposableBean's destroy 3. a custom destroy-method definition
|
· BeanNameAware
· Bean 이름으로 인식을 원하는 bean 구현할때 사용하는 interface이다.
· BeanClassLoaderAware
·
Callback that allows a bean to be
aware of the bean class loader
; that is, the class loader used by
the present bean factory to load bean classes.
· BeanFactoryAware
· Bean의 BeanFactory 인식을 위한 Interface
· EnvironmentAware
· 실행되는 Environment를 통지하고 싶은 bean
· Embedded definition values의 해결을 위해 StringValueResolver의 통지를 하고 싶은 오브젝트를 위한 Interface이다.
· ResourceLoader(ApplicationContext)의 알림을 받기 위한 인터페이스이다.
· ApplicationEventPublisherAware
· 실행되는 ApplicationEventPublisher (일반적으로 ApplicationContext)의 알림을 받기 위한 인터페이스이다.
· MessageSource (일반적으로 ApplicationContext)의 알림을 받기 위한 인터페이스
· Parameterization과 internationalization의 메시지 제공
· ApplicationContext를 실행할 때 알림을 받기 위한 인터페이스
· ApplicationObjectSupport는 이 인터페이스를 구현한 기본클래스이다.
· ServeltContext(일반적으로 WebApplicationContext) 구동시 알림을 받기 위한 인터페이스
·
BeanPostProcessor
새로운 bean
instance를 생성할 때 사용자의 수정을 허용하는 hook이다.
ApplicationContexts는 BeanPostProcessor Bean을 Bean 정의에서 자동 탐지하여 이후에 작성된 Bean에 적용 할 수 있습니다
Factory 를 통해 생성된 모든 Bean에 적용된다.
· postProcessBeforeInitialization : Bean 초기화 콜백후에
· postProcessAfterInitialization: Bean 초기화 콜백 후에
BeanFactory에 의해 모든 속성이 설정되면 반행해야할 bean에 구현해야할 인터페이스
afterPropertiesSet()
모든 bean속성을 설정하고 BeanFactory에 의해 호출된다.
ApplicationContext
Application을 설정을 제공하기 위한 중심 interface이다.
실행 중에는 읽기전용이며, 구현으로 reaload가 가능한다.
제공 기능
l Components의 access을 위한 bean factory 함수 제공(ListableBeanFactory상속)
l File resource에서 로드하는 기능(ResourceLoader상속)
l 등록된 listener에 publish하는 기능(ApplicationEventPublisher상속)
l Internationalization 지원을 위한 message resolve 기능(MessageSource상속)
l 부모Context를 상속. 하위context가 우선순위를 가진다.
l 하나의 부모context는 전체웹어플리케이션에서 사용되며 각 서블릿은 독립된 자체컨텍스를 가질 수 있다.
BeanFacory의 lifecycle기능의 표준과 , ApplicationContexetAware, ResourceLoaderAware, ApplicationEventAware,MessageSourceAware의 구현 감지 및 호출을 제공한다.