核心问题:
怎么在javaWeb中使用spring配置的bean
只需要导入spring必须的包即可
方式1.使用自己手动创建ServletContextListener实现类的方式,并手动放入application域中
note.txt
Spring整合Struts21.怎么在web应用的组件中使用IOC容器01.在web应用被加载时创建ApplicationContext,把applicationContext放入到application域中(即servletContext的属性中)001.把spring的配置文件的位置作为web应用的初始化参数
configLocation
applicationContext.xml
002.创建ServletContextListener的实现类,在void contextInitialized(ServletContextEvent arg0)方法中//1.得到servletContext
ServletContext servletContext =arg0.getServletContext();//2.得到在web.xml中配置的spring配置文件的位置信息
String configLocation = servletContext.getInitParameter("configLocation");//1.得到ApplicationContext
ApplicationContext ctx = newClassPathXmlApplicationContext(configLocation);//2.把ctx加到application域中
servletContext.setAttribute("ctx", ctx);02.在servlet中就可以通过
ApplicationContext ctx= (ApplicationContext) this.getServletContext().getAttribute("ctx");访问
方式2.使用spring自动创建ServletcontextListener,并自动放入到application域中
其实还可以用spring自带的方式来实现在web应用中使用applicationContext1.写好model类和spring的配置文件2.在web.xml中直接alt+/选择#contextLoaderListener,就会出现
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
3.在web中的访问方式
ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(application);
Person person= (Person) ctx.getBean("person");
System.out.print(person);
WebApplicationContextUtils这个工具类是spring实现的