Spring BeanNameAware Interface


BeanNameAware Interface




스프링에서 관리되는 bean 내부에서 id나 name이 무엇으로 지정되어 있는지 확인하는 경우 BeanNameAware Interface를 구현한다. 이때 그림의 노란색 부분처럼 bean생성과 property 의존성 주입을 완료한 이후, init method를 수행하기 전 시점에 호출된다. 주로 로그메시지에서 문제가 되는 bean의 id를 출력하는 경우나 테스트 진행 시 유용한 기능이다.


용도

  • bean 내부에서 자신이 지정된 id, name을 확인 하는 경우 사용
  • 주로 log의 품질을 높이거나 에러 추적에 사용

 




사용방법

  • BeanNameAware 구현하고, setName() 메서드 override하는 경우 bean의 id, name이 매개변수로 전달
  • bean내부에서 이를 저장하거나 logging 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.spring.bean;
 
import org.springframework.beans.factory.BeanNameAware;
 
public class SimpleClass implements BeanNameAware{
 
    private String name;
    
    @Override
    public void setBeanName(String name) {
        System.out.println("BeanNameAware.setBeanName() 호출 됨 : name = " + name);
        this.name = name;
    }
    
    public String getName() {
        return this.name;
    }
 
}
cs

 

 이외에 별도 설정은 없으며, xml방식이나 annotation방식이나 설정 방법은 동일하다. 만약, bean정의시 id가 정의되지 않았다면 name으로 지정된 값이 setName()에 전달된다.



다운로드


SpringBeanNameAwareXml.zip


SpringBeanNameAwareAnnotation.zip


'프로그래밍 > Spring FWK' 카테고리의 다른 글

Spring PropertyEditor  (0) 2016.01.05
Spring facoty-bean, factory-method  (0) 2015.12.30
Spring FactoryBean Interface  (0) 2015.12.29
Spring ApplicationContextAware Interface  (0) 2015.12.28
Spring Bean Life Cycle (빈 생명주기 관리)  (0) 2015.12.28
Spring bean 상속  (0) 2015.12.27
Spring Bean Scope 정리  (0) 2015.12.27
Spring Method Replace (replaced-method)  (0) 2015.12.18

이 글을 공유하기

댓글

Email by JB FACTORY