web环境中:
web.xml中配置
contextConfigLocation
/WEB-INF/applicationContext.xml
webAppRootKey
petclinic.root4
org.springframework.web.context.ContextLoaderListener
jsp页面中取
Insert title hereApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
out.println(((DataCenterAction)ctx.getBean("dataCenterAction")).getPageSize());
%>
还有第二种方法:
WebApplicationContext wac = (WebApplicationContext)
config.getServletContext().getAttribute(WebApplicationContext.
ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
User u = (User) wac.getBean("user");
测试类中:
Resource res = new FileSystemResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
or
ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
or
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml", "applicationContext-part2.xml"});