Spring中ApplicationContextAware 的作用
阿新 • • 發佈:2018-11-15
ApplicationContextAware
通過它Spring容器會自動把上下文環境物件呼叫ApplicationContextAware
介面中的setApplicationContext
方法。
我們在ApplicationContextAware
的實現類中,就可以通過這個上下文環境物件得到Spring容器中的Bean。
看到—Aware就知道是幹什麼的了,就是屬性注入的,但是這個ApplicationContextAware的不同地方在於,實現了這個介面的bean,當spring容器初始化的時候,會自動的將ApplicationContext注入進來:
使用方法如下:
1.實現ApplicationContextAware介面:
import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import com.co.ayz.rpc.registry.ServiceRegistry; public class RpcServer implements ApplicationContextAware{ private ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // TODO Auto-generated method stub context = applicationContext; } //獲得applicationContext public static ApplicationContext getApplicationContext() { //assertContextInjected(); return context; } public static void clearHolder(){ context=null; } //獲取Bean public static <T> T getBean(Class<T> requiredType){ //assertContextInjected(); return (T) getApplicationContext().getBean(requiredType); } @SuppressWarnings("unchecked") public static <T> T getBean(String name){ assertContextInjected(); return (T) getApplicationContext().getBean(name); } //判斷application是否為空 public static void assertContextInjected(){ Validate.isTrue(context==null, "application未注入 ,請在springContext.xml中注入SpringHolder!"); } }
因為我們在做開發的時候,並不是說在每一個地方都能將屬性注入到我們想要的地方去的,比如在Utils使用到dao,我們就不能直接注入了,這個時候就是我們需要封裝springContext的時候了,而ApplicationContextAware就起了關鍵性的作用。