1. 程式人生 > >在任意bean中獲取spring上下文集合

在任意bean中獲取spring上下文集合

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.

大概意思是:任意想得到正在執行的 ApplicationContext  的物件需要實現該介面。

實現這個介面是有意義的,比如當一個物件請求訪問有協作關係的bean集合時,注意只能通過配置實現了這個介面的bean來查詢目標。

補充說明一下:如果實現了ApplicationContextAware介面,在Bean的例項化時會自動呼叫setApplicationContext()方法。

舉例:

public class Test implements ApplicationContextAware { 
public void setApplicationContext(ApplicationContext context) throws BeansException { 
Bean1 b = (Bean1) context.getBean("bean1"); 


System.out.println("列印 : " + b.getName());