核心问题:
怎么在javaWeb中使用spring配置的bean
只需要导入spring必须的包即可
方式1.使用自己手动创建ServletContextListener实现类的方式,并手动放入application域中
note.txt
Spring整合Struts2 1.怎么在web应用的组件中使用IOC容器 01.在web应用被加载时创建ApplicationContext,把applicationContext放入到application域中(即servletContext的属性中) 001.把spring的配置文件的位置作为web应用的初始化参数 <context-param> <param-name>configLocation</param-name> <param-value>applicationContext.xml</param-value> </context-param> 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 = new ClassPathXmlApplicationContext(configLocation); //2.把ctx加到application域中 servletContext.setAttribute("ctx", ctx); 02.在servlet中就可以通过 ApplicationContext ctx = (ApplicationContext) this.getServletContext().getAttribute("ctx");访问
方式2.使用spring自动创建ServletcontextListener,并自动放入到application域中
其实还可以用spring自带的方式来实现在web应用中使用applicationContext 1.写好model类和spring的配置文件 2.在web.xml中直接alt+/选择#contextLoaderListener,就会出现 <!-- needed for ContextLoaderListener --> <context-param> <param-name>contextConfigLocation</param-name> <!-- Spring ApplicationContext配置文件的路径,可以使用通配符*,多个路径用,号分隔 此参数用于后面的Spring ContextLoaderListener 多个配置文件生成是一个applicationContext --> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <listener>
<!-- spring实现的ServletContextListener类,会在web应用初始化的时候创建IOC容器并装配 --> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> 3.在web中的访问方式 ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application); Person person = (Person) ctx.getBean("person"); System.out.print(person);
WebApplicationContextUtils这个工具类是spring实现的