javaEE Spring,web项目中简单使用Spring;Spring容器配置,获取Spring容器

需要导入额外的jar包(web项目需要的Spring的jar包):spring-web-4.2.4.RELEASE.jar

web.xml(web项目的核心配置文件;通过监听器实现Spring容器在整个web中是单例的):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>MyWeb</display-name>
  <!-- 通过监听器Listener,可以让spring容器随web项目的启动而创建,随项目的关闭而销毁.(可以保证Spring容器是单例的) -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 指定创建Spring容器时,所需spring配置文件所在的位置/名字 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>  <!-- 是在src目录下 -->
  </context-param>
  
  <!-- struts2的核心过滤器 -->
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

CustomerAction.java(Struts2的Action中获取Spring容器):

package cn.xxx.web.action;

import javax.servlet.ServletContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

import cn.xxx.service.CustomerService;

public class CustomerAction extends ActionSupport {
	
	public String list() throws Exception {
		//获得spring容器=>从原生Application域获得即可
	
		//1 获得原生servletContext对象
		ServletContext sc = ServletActionContext.getServletContext();
		//2.从Sc中获得ac容器(Spring容器)
		WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
		//3.从容器中获得CustomerService对象
		CustomerService cs = (CustomerService) ac.getBean("customerService");
		
		//................................
		
		return "success";
	}
	
}

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/81978735