Java類如何獲取Spring的bean

學識都 人氣:3.03W

一個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 管理所有對象。