普通Java類獲取Spring的Bean的方法
在SSH集成的前提下。某些情況我們需要在Action以外的類中來獲得Spring所管理的Service對象。
之前我在網上找了好幾好久都沒有找到合適的方法。例如:
ApplicationContext context = new ClassPathXmlApplicationContext(); |
當時我覺得沒有這個必要,浪費內存。后來我終於想出了一個解決方法。在此拿來給大家參考下,希望對大家有幫助。
1.創建一個類並讓其實現org.springframework.context.ApplicationContextAware接口來讓Spring在啟動的時候為我們注入ApplicationContext對象.
示例代碼:
view plaincopy to clipboardprint? import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class MyApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext context;//聲明一個靜態變量保存 public void setApplicationContext(ApplicationContext contex) throws BeansException { this.context=contex; } public static ApplicationContext getContext(){ return context; } |
2.在applicationContext.xml文件中配置此bean,以便讓Spring啟動時自動為我們注入ApplicationContext對象.
例:
<!-- 這個bean主要是為了得到ApplicationContext 所以它不需要其它屬性--> <bean class="org.ing.springutil.MyApplicationContextUtil"></bean> |
3.有了這個ApplicationContext之后我們就可以調用其getBean("beanName")方法來得到由Spring 管理所有對象.