Spring框架入门

Spring框架

是一站式的轻量级的开源框架Spring

整合struts+Spring 其中Spring的作用是替代了传统的new的方式在action层和service层和dao层创建对象,将创建对象的工作交给了Spring容器去创建,并通过Set方法,注入

步骤,首先添加所需要的jar包,除了基本的Spring需要的4+2个jar包

两个日志包

4个基本包之外

还需要添加Spring-web-4.3.6-RELEAES..jar

首先在web.xml来书写这样一段代码以保证能够通过一个WebApplicationContext对象来获取javabean实例对象

 <!-- spring的过滤器加载 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
   <!-- 指定加载spring配置文件的位置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
在action层-service层把对象书写成成员属性,并封装Set方法

action 层

EmployeeService service ;//服务层的对象

// 3.声明服务层对象
    private UserService us;

service层

//声明dao层的对象

EmployeeDAO dao ;

//声明dao层对象

UserDAO userDAO ;

再书写applicationContext.xml中配置相应的bean属性和类路径

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://www.springframework.org/schema/beans" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

	<!-- 注入dao -->
	<bean name="empDAO" class="dao.jdbc.EmployeeDAOImpl"></bean>
	<bean name="userDAO" class="dao.jdbc.UserDAOImpl"></bean> 
	<!-- 注入service -->
	<bean name="employeeservice" class="service.EmployeeService">
		<property name="dao" ref="empDAO"></property>
	</bean>
	<bean name="userservice" class="service.UserService">
		<property name="userDAO" ref="userDAO"></property>
	</bean>

</beans>
在Action通过获取webApplicationContext方式来创建相应的对象EmployeeService

                ServletContext sc = ServletActionContext.getServletContext();
		//2.拿到application对象
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
		service = (EmployeeService) wac.getBean("employeeservice");
对象UserService

                 //1.拿到ServletContext对象
		ServletContext sc = ServletActionContext.getServletContext();
		//2.拿到application对象
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
		us = (UserService) wac.getBean("userservice");



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值