一、下载Spring包。官网地址:http://www.springsource.org/spring-community-download
二、解压后得到如下目录,其中docs中包含有API和spring使用说明。
三、在Eclipse中新建动态Web项目,将spring的jar包引入:
spring-core-3.2.3.RELEASE.jar 核心依赖jar包
spring-context-3.2.3.RELEASE.jar 容器包
spring-beans-3.2.3.RELEASE.jar beans的管理包
spring-expression-3.2.3.RELEASE.jar
另外还需加入commons-logging.jar
四、在web.xml中加入Spring的配置,只需加入一个listener和配置bean文件所在目录即可:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 默认配置在WEB-INF目录下 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/applicationContext.xml</param-value> <!-- <param-value>/WEB-INF/spring*.xml</param-value> -->
</context-param>
bean配置文件applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
default-autowire="byName" default-lazy-init="true">
<bean id="service" class="entity.DoServiceImpl"></bean>
</beans>
五、测试
新建一个Servlet如下,注意其中获取Bean的方式:
public class doServiceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//注意此处
private static WebApplicationContext webContext;
public doServiceServlet() {
super();
}
@Override
public void init() throws ServletException {
super.init();
ServletContext servletContext = this.getServletContext();
webContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
IService service = (IService) webContext.getBean("service");
service.doService();
}
}
或者直接在Java类中用main方法验证(ClassPathXmlApplicationContext默认路径为src下,另外还有FileSystemXmlApplicationContext可用):
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
IService service = (IService) ctx.getBean("service");
service.doService();
}
}