Spring動態獲取Bean
阿新 • • 發佈:2019-01-24
想要在普通的JAVA程式中動態地獲取Spring容器中的Bean,有若干種方法,下面是一種普遍使用的。
首先在上下文配置檔案(application.xml)配置:
<bean id="beanGetter" class="cn.jdfo.tool.BeanGetter">
<property name="beanGetter"><ref bean="beanGetter"></ref></property>
</bean>
我這裡取的名字是beanGetter
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class BeanGetter implements ApplicationContextAware{ private ApplicationContext applicationContext; private static BeanGetter beanGetter; private BeanGetter(){} public static BeanGetter getBeanGetter() { return beanGetter; } public void setBeanGetter(BeanGetter beanGetter) { BeanGetter.beanGetter = beanGetter; } public Object getBean(String beanName){ return applicationContext.getBean(beanName); } public <T> T getBean(String beanName, Class<T> tClass){ return applicationContext.getBean(beanName,tClass); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext=applicationContext; } }
在普通的java類中,可以直接通過下面一句獲取這個物件:
BeanGetter beanGetter=BeanGetter.getBeanGetter();
然後就可以呼叫getBean方法了。
其他獲取bean的幾種方式:
1、ClassPathXmlApplicationContext
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { "spring.xml" });
然後可以呼叫appContext.getBean()
2...