Java類如何獲取Spring的bean

才智咖 人氣:3.02W

一個Bean扮演著應用程式素材的角色。它包含有一個functional interface,一個life-cycle interface,以及一個實現它所支援的商業方法的類別。下面小編為大家整理了關於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物件.

例:

   

3.有了這個ApplicationContext之後我們就可以呼叫其getBean("beanName")方法來得到由Spring 管理所有物件。