2011-10-25 2 views
4

Spring의 빈 설정 파일에서 현재 애플리케이션 컨텍스트를 참조 할 수있는 방법이 있습니까?Spring XML에서 applicationcontext의 "this"참조

나는 이런 식으로 뭔가를 시도하고있다 :

<beans 
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> 

    <bean id="some-bean-name" class="com.company.SomeClass"> 
     <constructor-arg> 
      <!-- obviously this isn't right --> 
      <bean ref=#{this}/> 
     </constructor-arg> 
    </bean> 

문제는 SomeClass이 생성자에의 ApplicationContext 인스턴스를 필요로한다는 것이다. 콩을로드하는 ApplicationContext의 참조를 얻을 수있는 방법이 있습니까? XML에서 모든 로딩 작업을 수행 할 수 있다는 것을 알고 있지만 Java 코드에서 Bean 로딩을 수행해야하는 경우에는 그렇지 않습니다.

답변

1

ApplicationContextAware을 구현 했습니까? 생성자에 들어 가지 않지만 init() 호출 전에 발생하며 bean 특성이 채워진 직후에 발생합니다.

은 일반적인 bean 프라퍼티의 활성화 이후 호출하지만 같은 InitializingBean.afterPropertiesSet로 초기화 콜백 전() 또는 사용자 정의 초기화-방법. 적용 가능한 경우 ResourceLoaderAware.setResourceLoader (012.springframework.core.io.ResourceLoader), ApplicationEventPublisherAware.setApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher) 및 MessageSourceAware 뒤에 호출됩니다.

public class SomeClass implements ApplicationContextAware { 
    //your class definition 
    private ApplicationContext myContext; 

    public void setApplicationContext(ApplicationContext context) throws BeansException { 
     myContext = context; 
     //load beans here maybe? 
    } 
} 

할 수도 있습니다 만 @Autowire(d) 그 이후 스프링 2.5을 사용하는 경우.

public class SomeClass { 
    //your class definition 
    @Autowired 
    private ApplicationContext myContext; 
} 

물론 이들 중 하나를 수행하면 코드가 스프링에 연결됩니다.

+0

이 작업을 수행하기 위해 XML에서해야 할 일이 있습니까? 인터페이스 접근 방식을 시도하고 setter가 호출되지 않는 것 같습니다. – javamonkey79

+0

'SomeClass'는'ApplicationContext'에 의해 관리 될 필요가 있습니다. XML 구성 또는 주석 구성에 의해. –

+0

콩이 스프링으로로드되어있을 때만 작동합니다. 그렇지 않으면 수동으로 setter를 호출해야합니다. \ – javamonkey79