普通Java類獲取Spring的bean

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;//聲明一個靜態變量保存  
@Override 
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 管理所有對象.

 

 

原文地址:http://www.toedu.org/Article/Java/Article_602.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章