반응형

 

 

 

 

Spring Container의 bean 관리

- bean 객체의 생성, 의존 객체 주입 및 초기화, 객체 삭제 등 객체 life-cycle에 관련된 작업을 수행한다.

- 각 bean에 대해 callback method를 호출하여 실행함(호출의 주체가 '시스템')

* bean 클래스에 life-cycle 관련된 callback method가 구현된 경우, container가 적절한 시점에 메소드를 호출함

ex) BeanNameAware#setBeanName(String beanName), InitializingBean#afterPropertiesSet()

 

* 자체적으로 정의된 custom init/destroy method 호출

<bean>의 init-method, destroy-method 속성으로 지정된 메소드

@Bean의 initMethod, destroyMethod 속성으로 지정된 메소드

@PostConstruct, @PreDestroy가 적용된 메소드

 

 

 

전체 life-cyle process

 

 

ApplicationContext container의 수행 절차

 

 

 

 

 

Life-cycle 관련 interfaces 및 callback methods

- BeanNameAware

void setBeanName(String beanName) ; id/name 속성을 전달

- BeanFactoryAware

void setBeanFactory(BeanFactory factory) : 자신을 관리하는 beanFactory 객체를 전달

- ApplicationContextAware

void setApplicationContext(Application context) : 자신을 관리하는 applicationContext 객체를 전달

 

예시)

 

 

 

Custom init-method

- Bean 객체 생성 및 DI 수행 후에 호출되는 메소드

- Bean 객체를 삭제하기 전에 호출되는 메소드

 

 

 

- Spring interfaces

 

 

- <bean> @Bean 설정 

 

 

 

 

 

 

 

Bean Scoping

Spring container는 기본적으로 한 개의 bean instance만을 생성(singleton)

Scope 지정 방법 : <bean>의 scope 속성 또는 @Scope annotaion 사용

 

 

Singleton vs Prototype

 

 

 

@Scope annotation 사용 예

 

 

 

 

외부 설정 Property

설정 정보의 외부화

Spring에서 bean 설정에 사용되는 설정 값을 외부의 환경변수나 파일 등에 별도의 property로 저장하고 사용하는 방법

ex) 데이터베이스 구성 정보 등

 

외부에 정의된 property 이용 방법

1) PropertyPlaceholderConfigurer 

-> <context:property-placeholder />

2) Environment 및 PropertySource 이용

 

 

 

PropertyPlaceholderConfigurer 

객체를 통해 외부에 존재하는 property file을 읽어들임(loading)

 

 

XML 기반 설정

- PropertyPlaceholderConfigurer 타입의 객체를 bean으로 생성

- property file의 목록을 location 또는 locations 속성의 값으로 제공

- property file에 정의된 각 property는 ${property-name} 형식으로 참조

 

 

 

 

- 주의사항 : <context:pro...> 가 두 번 이상 사용될 경우 먼저 처리된 설정만 적용됨

- 해결방법

 

 

 

 

JavaConfig 기반 설정

@PropertySource, @PropertySources annotation 이용

 

 

 

Environment를 통한 property 이용

 

 

 

Bean에서 Environment 클래스 이용하는 방법

방법 1) EnvironmentAware interface 구현

 

 

 

방법 2) @Autowired 를 통한 Environment 객체 자동 주입

 

 

 

 

 

 

 

Message Source 

텍스트 메시지들을 프로그램 내에 직접 작성하지 않고 외부 property file에 저장 후 참조

 

Message bundle 정의 및 활용

 

 

 

ApplicationContext 가 위의 인터페이스를 상속하고 AbstractApplicationContext 클래스가 구현

 

 

 

 

 

 

Bean 객체에서 Message 참조 방법

방법 1) MessageSourceAware 인터페이스 구현

 

 

방법 2) ApplicationContextAware 인터페이스 구현 (MessageSourceAware 의 상위 클래스)

 

 

 

 

반응형

'Programming > Spring' 카테고리의 다른 글

06. Spring Boot  (0) 2021.05.27
05. Spring MVC  (0) 2021.04.18
03. Auto-wiring, Java code 기반 설정, annotation 기반 설정  (0) 2021.04.13
02. SpringDI / 생성자 * setter 방식 / SpEL  (0) 2021.04.06
01. Spring Framework 개요  (0) 2021.04.04

+ Recent posts