2011-10-25 44 views
4

有什麼辦法在Spring的bean配置文件中引用當前的應用程序上下文嗎?Spring的applicationcontext的「this」引用XML

我試圖做這樣的事情:

<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實例。有沒有什麼辦法來獲取加載bean的ApplicationContext的引用?我知道我可以在XML中完成所有的加載操作,但這並不完全符合我的要求,因爲我需要在我的Java代碼中進行Bean加載。

回答

1

你看過執行ApplicationContextAware嗎?它不在構造函數中,但它在init()調用之前發生,並且會在填充bean屬性之後發生。

正常bean屬性的人口後進行調用但一個init 回調如InitializingBean.afterPropertiesSet()之前或者定製 初始化方法。調用 ResourceLoaderAware.setResourceLoader(org.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? 
    } 
} 

您也可以直接​​如果使用Spring 2.5或更高版本的。

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

當然,執行其中任何一項都會將您的代碼綁定到Spring。

+0

有什麼你必須做的XML在做這項工作?我嘗試了接口方法,並且setter似乎沒有被調用。 – javamonkey79

+0

'SomeClass'需要由'ApplicationContext'管理。通過xml配置或註釋配置。 –

+0

我想我現在看到它,它只在豆子彈簧加載時才起作用,否則你必須手動調用setter。\ – javamonkey79

相關問題