本文共 8307 字,大约阅读时间需要 27 分钟。
获得spring里注册Bean的四种方法,特别是第三种方法,简单:
一:方法一(多在struts框架中)继承BaseDispatchAction二:方法二实现BeanFactoryAware 一定要在spring.xml中加上:<bean id="serviceLocator" class="项目中ServiceLocator的类路径比如:com.am.oa.commons.service.SpringContextUtil " singleton="true" />当对serviceLocator实例时就自动设置BeanFactory,以便后来可直接用beanFactory action调用:
三:方法三实现ApplicationContextAware 一定要在spring.xml中加上:<bean id="SpringContextUtil " class="项目中applicationContext的类路径比如:com.am.oa.commons.service.SpringContextUtil " singleton="true" />当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext
action调用:
四.通过servlet 或listener设置spring的ApplicationContext,以便后来引用.
注意分别extends ContextLoaderListener和ContextLoaderServlet .然后就可用SpringContext来getBean.覆盖原来在web.xml中配置的listener或servlet.
自己使用:
1.如果applicationContext文件是在src的根目录下:
ApplicationContext apt= new FileSystemXmlApplicationContext("src/applicationContext.xml");
apt.getBean("ID");
可以取得
2.如果文件是在WebRoot/WEB-INF下可以用
ApplicationContext applicationContext= new FileSystemXmlApplicationContext("../applicationContext.xml");
取得
3.如果是在servlet中取可用
ServletContext application = this.getServletContext();
//获取spring上下文信息 为servlet使用 WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application); IDicService dicService = (IDicService)wac.getBean("dicService");
转载地址:http://tclpi.baihongyu.com/