web开发中,一般采用spring框架来管理DAO层和Service层中的bean,当需要使用这些bean的时候,spring会利用其IOC来帮我们注入这些bean。然后,我们可以直接拿着bean狂用。但是如果需要在不是由spring管理的java类中使用这些bean怎么办,经过参考了一些资料后,整理出一个获取bean的工具类。
获取由spring管理的bean的工具类如下:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class GetBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
private GetBeanUtil() {
super();
}
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
applicationContext = arg0;
}
public static Object getBean(String paramString) {
return applicationContext.getBean(paramString);
}
}
使用:
// 获取bean goodsService
GoodsService goodsService = (GoodsService) GetBeanUtil.getBean("goodsService");
之后就任你调用了。