DI 없이 스프링 빈이 아닌 일반 스레드 컨텍스트에서 스프링 컨테이너 내부의 빈 가져오기

Jake Seo·2021년 2월 18일
0

문제해결잡지식

목록 보기
17/20

문제

계속 DI를 이용해서 스프링 컨테이너의 빈을 가져와버릇해서, DI없이 가져오는 방법을 잘 몰랐다.

해결

Provider 생성

위와 같이, static하게 ApplicationContext를 접근할 수 있도록 해준다. ApplicationContextAware를 상속받아 setApplicationContext를 오버라이드 해준다.

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
Implementing this interface makes sense for example when an object requires access to a set of collaborating beans. Note that configuration via bean references is preferable to implementing this interface just for bean lookup purposes.
This interface can also be implemented if an object needs access to file resources, i.e. wants to call getResource, wants to publish an application event, or requires access to the MessageSource. However, it is preferable to implement the more specific ResourceLoaderAware, ApplicationEventPublisherAware or MessageSourceAware interface in such a specific scenario.
Note that file resource dependencies can also be exposed as bean properties of type org.springframework.core.io.Resource, populated via Strings with automatic type conversion by the bean factory. This removes the need for implementing any callback interface just for the purpose of accessing a specific file resource.
org.springframework.context.support.ApplicationObjectSupport is a convenience base class for application objects, implementing this interface.
For a list of all bean lifecycle methods, see the BeanFactory javadocs.
See Also:
ResourceLoaderAware, ApplicationEventPublisherAware, MessageSourceAware, org.springframework.context.support.ApplicationObjectSupport, org.springframework.beans.factory.BeanFactoryAware
Author:
Rod Johnson, Juergen Hoeller, Chris Beams

위와 같은 주석이 있는데 해석하면

클래스에는 아래와 같은 주석이 있고,

ApplicationContext가 내부적으로 동작하는 것을 알리고 싶은 오브젝트에 구현해야 하는 인터페이스.

이 인터페이스를 구현하는 것은 이를테면 오브젝트가 공동작업하는 빈의 집합에 접근이 필요할 때 합리적입니다. 그냥 단순히 빈을 찾는 목적으로는 빈 관계를 통한 설정이 이 인터페이스를 구현하는 것보다 더 선호됩니다.

이 인터페이스는 만일 오브젝트가 파일 리소스에 (이를테면 getResource를 호출하길 원할 때, 어플리케이션 이벤트를 발행하고 싶을 때 또는 MessageSource에 접근이 필요할 때) 접근할 필요가 있을 때 구현될 수 있습니다. 하지만, 위와 같은 경우에도 더 상세히 ResourceLoaderAware 혹은 ApplicationEventPublisherAware 혹은 MessageSourceAware 인터페이스를 구현하는 것이 더 선호됩니다.

파일 리소스 의존성은 빈 팩토리에 의한 자동적인 타입 변환과 함께String들을 통해 생성된 org.springframework.core.io.Resource 타입의 빈 프로퍼티로 노출될 수 있습니다. 위와 같은 특성은 특정한 파일 리소스에 접근하는 목적을 위해 어떤 콜백 인터페이스를 구현할 필요를 없애줍니다.

setApplicationContext에는 아래와 같은 주석이 있다.

이 오브젝트가 동작하는 내부의 어플리케이션 컨텍스트를 세팅하세요. 일반적으로 이러한 호출은 오브젝트를 초기화 하는데 이용됩니다.

일반 빈 프로퍼티들의 생성 이후에 호출되지만, org.springframework.beans.factory.InitializingBean.afterPropertiesSEt() 또는 사용자 정의 초기화 메소드 초기화 콜백 전에 호출되기도 합니다. 가능한 경우에는 ResourceLoaderAware.setResourceLoader, ApplicationEventPublishAware, setApplicationEventPublisherMessageSourceAware 이후에 호출됩니다.

BeanUtils 생성

이용하기

profile
풀스택 웹개발자로 일하고 있는 Jake Seo입니다. 주로 Jake Seo라는 닉네임을 많이 씁니다. 프론트엔드: Javascript, React 백엔드: Spring Framework에 관심이 있습니다.

0개의 댓글