獲取Spring中的bean有很多種方式,在此總結一下:
第一種:在初始化時保存ApplicationContext對象
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");
說明:這種方式適用於采用Spring框架的獨立應用程序,需要程序通過配置文件手工初始化Spring。
import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");
說明:第三種:繼承自抽象類ApplicationObjectSupport
說明:通過抽象類ApplicationObjectSupport提供的getApplicationContext()方法可以方便的獲取到ApplicationContext實例,進而獲取Spring容器中的bean。Spring初始化時,會通過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 對象注入。
第四種:繼承自抽象類WebApplicationObjectSupport
說明:和上面方法類似,通過調用getWebApplicationContext()獲取WebApplicationContext實例;
第五種:實現接口ApplicationContextAware
說明:實現該接口的setApplicationContext(ApplicationContext context)方法,並保存ApplicationContext對象。Spring初始化時,會通過該方法將ApplicationContext對象注入。
雖然Spring提供了後三種方法可以實現在普通的類中繼承或實現相應的類或接口來獲取Spring的ApplicationContext對象,但是在使用時一定要注意繼承或實現這些抽象類或接口的普通java類一定要在Spring的配置文件(即application-context.xml文件)中進行配置,否則獲取的ApplicationContext對象將為null。
下面通過實現接口ApplicationContextAware的方式演示如何獲取Spring容器中的bean:
首先自定義一個實現了ApplicationContextAware接口的類,實現裡面的方法:
package com.ghj.tool;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringConfigTool implements ApplicationContextAware {// extends ApplicationObjectSupport{
private static ApplicationContext ac = null;
private static SpringConfigTool springConfigTool = null;
public synchronized static SpringConfigTool init() {
if (springConfigTool == null) {
springConfigTool = new SpringConfigTool();
}
return springConfigTool;
}
public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
ac = applicationContext;
}
public synchronized static Object getBean(String beanName) {
return ac.getBean(beanName);
}
}
其次在applicationContext.xml文件進行配置:最後通過如下代碼就可以獲取到Spring容器中相應的bean了:
SpringConfigTool.getBean("beanId");
注意一點,在服務器啟動Spring容器初始化時,不能通過以下方法獲取Spring容器:import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); wac.getBean(beanID);