Web项目中引入Spring

一、下载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();
	}
}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值