JSP 獲取spring容器中bean的方法總結(jié)
方案1(Web中使用):
ApplicationContext ct = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext()); logService = (ISysLogService) ct.getBean("sysLogServiceImpl");
說明:getRequiredWebApplicationContext方法中需要傳入ServletContext()對(duì)象,在struts2中可以這樣獲取:
ServletActionContext.getServletContext()
方案2(通過手動(dòng)啟動(dòng)spring容器后獲取,如果在web中,不建議這樣使用):
//匹配多個(gè)文件
ApplicationContext ct = new FileSystemXmlApplicationContext(new String[] { "classpath:applicationContext.xml","classpath:lb/*/applicationContext-*.xml"});
//加載一個(gè)文件
ApplicationContext ct = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
注:獲取spring容器中bean的方法還有幾個(gè),這里就不一一列舉了,個(gè)人認(rèn)為這兩個(gè)是最直接最簡(jiǎn)單的。