ApplicationContextAware是在org.springframework.context包下的一個(gè)接口糟描,用于獲取spring的上下文,顧名思義,可用通過(guò)這個(gè)接口獲取到spring的上下文context,通俗的講父叙,就是能通過(guò)實(shí)現(xiàn)這個(gè)接口來(lái)獲取到spring的IOC容器中的各個(gè)bean,具體實(shí)現(xiàn)如下兩步。
/**
*ApplicationContextAware 接口定義
*/
public abstract interface org.springframework.context.ApplicationContextAware {
public abstract void setApplicationContext(org.springframework.context.ApplicationContext context) throws org.springframework.beans.BeansException;
}
1趾唱、通過(guò)這個(gè)接口的定義可以發(fā)現(xiàn)涌乳,實(shí)現(xiàn)本接口需要重寫setApplicationContext方法。
public class SMSContextInit implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public ApplicationContext getApplicationContext() {
return applicationContext;
}
//重寫接口中的方法
public void setApplicationContext(ApplicationContext aContext) {
applicationContext = aContext;
}
/**
* 通過(guò)beanId得到factory中的bean實(shí)例
* @param beanId
* @return Object
*/
public static Object getBean(String beanId) {
Object obj = null;
if (applicationContext != null)
obj = applicationContext.getBean(beanId);
return obj;
}
}
2甜癞、在spring的配置文件中需要配置實(shí)現(xiàn)類給spring管理夕晓。
<bean class="gnnt.MEBS.integrated.mgr.utils.SMSContextInit" />
通過(guò)實(shí)現(xiàn)的過(guò)程不難發(fā)現(xiàn),ApplicationContextAware獲取上下文的步驟就是带欢,先把實(shí)現(xiàn)類SMSContextInit 交給spring管理运授,是spring容器發(fā)現(xiàn)SMSContextInit 是ApplicationContextAware的實(shí)現(xiàn)類,則調(diào)用setApplicationContext方法把上下文的引用交給SMSContextInit 類來(lái)使用乔煞。
另外:
spring雖然提供了ApplicationContextAware接口來(lái)使用吁朦,但是從耦合性的層面上來(lái)看,實(shí)現(xiàn)這個(gè)接口相當(dāng)于把實(shí)現(xiàn)類和spring框架嚴(yán)格的綁定在一起了渡贾,有違低耦合的思想逗宜。其實(shí)要實(shí)現(xiàn)低耦合的獲取spring上下文也是可以實(shí)現(xiàn)的,ApplicationContextAware其實(shí)就是使用的setter注入的思想空骚,那么獲取上下文的操作同樣可以用setter注入的方式來(lái)實(shí)現(xiàn)纺讲,代碼改寫如下:
public class SMSContextInit {
private static ApplicationContext applicationContext;
public ApplicationContext getApplicationContext() {
return applicationContext;
}
//setter方法用來(lái)實(shí)現(xiàn)context的注入
public void setApplicationContext(ApplicationContext aContext) {
applicationContext = aContext;
}
/**
* 通過(guò)beanId得到factory中的bean實(shí)例
* @param beanId
* @return Object
*/
public static Object getBean(String beanId) {
Object obj = null;
if (applicationContext != null)
obj = applicationContext.getBean(beanId);
return obj;
}
}