Web/Spring 2019. 2. 25. 15:57

Spring - ApplicationContext,ApplicationContextAware, 빈이 아닌 객체에 빈주입할때!



@Autuwired,@Inject 등의 어노테이션으로 의존주입을 하기 위해서는 해당 객체가 빈으로 등록되어 있어야만 가능하다.

사실 이런 상황은 웹프로그래밍에서는 거의 없겠지만... 빈으로 등록되지 않은 객체에 빈으로 등록된 객체를 의존주입해야할 상황이 있을 수도 있다.

 그럴때 사용할수 있는 하나의 UtilClass 이다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Service
public class BeanUtils implements ApplicationContextAware {
 
    private static ApplicationContext context;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // TODO Auto-generated method stub
        context = applicationContext;
    }
 
    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }
}
cs


ApplicationContextAware를 구현한 BeanUtils 클래스를 하나 만들었다. 그리고 setApplicationContext() 메소드로 ApplicationContext를 

주입받고 있는 상황이다. 그리고 static으로 선언된 getBean 메소드를 이용하여 빈주입을 원하는 어딘가에서


BeanUtils.getBean()를 호출하여 빈을 주입받을 수 있다.!

posted by 여성게
: