




已阅读5页,还剩23页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Spring是什么?Spring是一个开源的控制反转(Inversion of Control ,IoC)和面向切面(AOP)的容器框架.它的主要目得是简化企业开发.IOC 控制反转 :例如:public class PersonAction private IPersonDao personDao = new PersonDao(); public void addPerson() personDao.save(person); PersonDao是在应用内部创建及维护的。所谓控制反转就是应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护是由外部容器负责的。这样控制权就由应用转移到了外部容器,控制权的转移就是所谓反转。依赖注入(Dependency Injection):当我们把依赖对象交给外部容器负责创建,那么PersonAction 类可以改成如下:public class PersonAction private IPersonDao personDao ;/ 提供getter setter方法 /通过setter构造器注入 所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中。如果使用Spring, 我们就不再需要手工控制事务(AOP)例如: / spring 开启事物 Session.save(user)/ spring 提交事物/ spring 关闭sessionSpring带给我们好处:1. DI依赖注入,降低程序之间的耦合度2. AOP面向方面编程,解决一些公共特性问题,例如,日志,事物开发spring框架:1.使用Spring需要的jar到/download下载spring,然后进行解压缩,在解压目录中找到下面jar文件,拷贝到类路径下distspring.jarlibjakarta-commonscommons-logging.jar如果使用了切面编程(AOP),还需要下列jar文件lib/aspectj/aspectjweaver.jar和aspectjrt.jarlib/cglib/cglib-nodep-2.1_3.jar如果使用了JSR-250中的注解,如Resource/PostConstruct/PreDestroy,还需要下列jar文件libj2eecommon-annotations.jar2.在 src下 创建applicationContext.xml文件:.该配置模版可以从spring的参考手册或spring的例子中得到。配置文件的取名可以任意,文件可以存放在任何目录下,但考虑到通用性,一般放在类路径下。3. com.spring.person.dao 包 public interface IPersonDao public void save();4. com.spring.person.dao.impl包:public class PersonDao implements IPersonDao public PersonDao()System.out.println(PersonDao 无参构造函数);public void save() System.out.println(-personDao save()方法-);public void init()System.out.println(personDao 初始化方法);public void destroy()System.out.println(personDao 销毁方法);5. 修改application.xml文件,添加如下内容:6. 测试 使用Junit单元测试(企业级单元测试)1 导包junit4.12 新建com.spring.person.test.PersonDaoTest(测试类 取名 要测试类+Test) 3 PersonDaoTest 创建 测试方法 方法名 : test+要测试类的方法4 例如:public void testSave()5 右键 点击方法 Run as junit test (注意: 红条表示测试失败,绿条表示测试成功)实例化spring容器实例化Spring容器常用的两种方式:方法一:在类路径下寻找配置文件来实例化容器ApplicationContext ctx = new ClassPathXmlApplicationContext(new StringapplicationContext.xml);方法二:在文件系统路径下寻找配置文件来实例化容器ApplicationContext ctx = new FileSystemXmlApplicationContext(new String“d: applicationContext.xml“);PersonDaoTest测试类testSave方法测试:BeanFactory/ApplicationContext/ AbstractApplicationContext factory=new ClassPathXmlApplicationContext(applicationContext.xml);IPersonDao personDao=(IPersonDao) factory.getBean(personDao);personDao.save();/ 或者BeanFactory factory=new FileSystemXmlApplicationContext(C:my_projSpring_TestsrcapplicationContext.xml);IPersonDao personDao=(IPersonDao) factory.getBean(personDao);personDao.save(); Bean的作用域(后期与struts集成时很重要)例如: .singleton 在每个Spring IoC容器中一个bean定义只有一个对象实例。默认情况下会在容器启动时初始化bean, bean默认设置成scope=singleton 时 当IOC容器加载时 就实现初始化(加载时初始化).prototype 每次从容器获取bean都是新的对象。bean设置成scope=prototype 时 当调用getBean时才实现初始化 (就要用的时候初始化)测试:public PersonDao()/ 提供无参构造函数System.out.println(PersonDao 无参构造函数);运行:BeanFactory factory= new ClassPathXmlApplicationContext(applicationContext.xml);IPersonDao personDao= (IPersonDao) factory.getBean(personDao);IPersonDao personDao1= (IPersonDao) factory.getBean(personDao);personDao.save();扩充:使用scope=singleton 调用getBean 初始化呢?有的,在bean属性中 lazy-init=true 实现懒加载 就会在IOC容器初始化时不加载指定Bean的初始化方法和销毁方法PersonDao类:public void init()System.out.println(personDao 初始化方法);public void destroy()System.out.println(personDao 销毁方法);测试:AbstractApplicationContext aac= new ClassPathXmlApplicationContext(applicationContext.xml);IPersonDao personDao= (IPersonDao) aac.getBean(personDao);personDao.save();aac.close();/关闭IOC容器 调用Bean的销毁方法依赖注入分为三种:1. 接口注入2. 构造函数注入3. setter注入4. 菜用注解方式实现注入接口注入:1. com.spring.person.action包PersonAction类:public class PersonAction private IPersonDao personDao;public String save()personDao.save();return success;public IPersonDao getPersonDao() return personDao;public void setPersonDao(IPersonDao personDao) System.out.println(setPersonDao();this.personDao = personDao;2. 修改applicationContext.xml文件: 3.测试:public void testPersoActionSave()/ 接口注入 AbstractApplicationContext aac= new ClassPathXmlApplicationContext(applicationContext.xml);PersonAction pa=(PersonAction) aac.getBean(personAction);pa.save();构造函数注入:1. com.spring.person.bean包Person类:public class Person / 构造函数注入 private int personId; private String personName; public Person(); public Person(int personId,String personName) this.personId=personId; this.personName=personName; public int getPersonId() return personId;public String getPersonName() return personName;2. 修改applicationContext.xml文件: 3. 测试: public void testPerson()/ 构造函数注入AbstractApplicationContext aac= new ClassPathXmlApplicationContext(applicationContext.xml);Person person=(Person)aac.getBean(person);System.out.println(personId=+person.getPersonId()+,personName=+person.getPersonName();setter注入:1. com.spring.user.bean包User类:public class User private int uid;private String userName;private Person person;private List list;private Map map;public int getUid() return uid;public void setUid(int uid) this.uid = uid;public String getUserName() return userName;public void setUserName(String userName) this.userName = userName;public Person getPerson() return person;public void setPerson(Person person) this.person = person;public List getList() return list;public void setList(List list) this.list = list;public Map getMap() return map;public void setMap(Map map) this.map = map;2. 修改applicationContext.xml文件: 张三 李四 王五 3测试:(新建UserTest类)public void testUser() / setter注入AbstractApplicationContext aac= new ClassPathXmlApplicationContext(applicationContext.xml);User user=(User) aac.getBean(user);System.out.println(uid=+user.getUid();System.out.println(userName=+user.getUserName();System.out.println(list集合:);for(String str : user.getList()System.out.print(str+ );System.out.println(map集合:);for(Map.Entry entry: user.getMap().entrySet()System.out.println(entry.getKey()+=+entry.getValue();System.out.println(person对象:);System.out.println(personId=+user.getPerson().getPersonId()+,personName=+user.getPerson().getPersonName();菜用注解方式实现注入(spring2.5推出):实例:1. com.spring.user.dao包:IUserDao接口:public interface IUserDao public User login(String userName,String password);2. com.spring.user.dao.impl包:public class UserDao implements IUserDaopublic User login(String userName, String password) System.out.println(处理登录);return null;3. 修改applicationContext.xml文件: (注意修改命名空间 不然会出错) 4. com.spring.user.action包:public class UserAction Resource(name=userDao)private IUserDao userDao;public String login()userDao.login(zhangsan, zhangsan);return success;5. 测试:public void testUser1()AbstractApplicationContext aac= new ClassPathXmlApplicationContext(applicationContext.xml);UserAction userAction=(UserAction) aac.getBean(userAction);userAction.login();采用注解Spring2.5自动扫描(重点核心技术):1. com.spring.teacher.dao包:public interface ITeacherDao public void addTeacher();2. com.spring.teacher.dao.impl包:Repositorypublic class TeacherDao implements ITeacherDao public void addTeacher() System.out.println(处理添加Teacher数据);3. com.spring.teacher.action包:Controller(teacherAction)public class TeacherAction Resource(name=teacherDao)private ITeacherDao teacherDao;public String add()teacherDao.addTeacher();return success;4. 修改applicationContext.xml文件: 开启spring2.5自动扫描 5. 测试:public class TeacherTest extends TestCase public void testAddTeacher() AbstractApplicationContext aac=new ClassPathXmlApplicationContext(applicationContext.xml); TeacherAction ta= (TeacherAction) aac.getBean(teacherAction); ta.add(); spring IOC 实现依赖注入结束Aop面向方面编程1. JDK动态代理2. 使用CGLIB生成代理首先讲讲spring底层实现原理JDK动态代理:新建项目有 spring_aop(导包.)1. com.aop.util包:JDKProxy类:/* * jdk动态代理 实现Aop思想 * author Administrator * */public class JDKProxy implements InvocationHandler private Object targetObject; public Object createProxyInstance(Object targetObject)this.targetObject=targetObject;/* * 第一个参数:目标类的类加载器 * 第二个参数: 目标类的接口 * 第三个参数设置回调对象,当代理对象的方法被调用时,会委派给该参数指定对象的invoke方法 */return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),targetObject.getClass().getInterfaces(),this);/* * 第一个参数:目标对象 * 第二个参数: 目标方法 * 第三个参数: 目标方法参数 * */public Object invoke(Object target, Method method, Object arg)throws Throwable TransationManager tm=new TransationManager();/切面类try tm.startTransation();/ 前置通知/ 调用目标方法Object obj = method.invoke(targetObject, arg);/ 切入点mitTransation();/ 后置通知 return obj; catch (RuntimeException e) e.printStackTrace();tm.rollbackTansation(); / 异常通知finallytm.closeSession();/ 最终通知return null;TransationManager类:public class TransationManager / 切面类 public void startTransation() System.out.println(开启事务); public void commitTransation() System.out.println(提交事务); public void rollbackTansation() System.out.println(回滚事务); public void closeSession() System.out.println(关闭session); 测试:public void testJDK()JDKProxy jdkProxy=new JDKProxy();IPersonDao personDao=(IPersonDao) jdkProxy.createProxyInstance(new PersonDao();personDao.addPerson(张三);使用CGLIB生成代理:public class CGLIBProxy implements MethodInterceptor private Object targetObject;public Object createProxyInstance(Object targetObject)this.targetObject=targetObject;/1. cglib库中 创建代理方式Enhancer enhancer=new Enhancer();/2. 设置目标类(让代理类派生子类),并重写 目标类的非final方法enhancer.setSuperclass(targetObject.getClass();/3.设置回调方法enhancer.setCallback(this);/4. 创建代理类,这个代理类是目标类的子类return enhancer.create();/* * 第一个参数: 目标对象 * 第二个参数: 目标方法 * 第三个参数: 目标方法参数 * 第四个参数:代理类对象的方法 */public Object intercept(Object target, Method method, Object arg,MethodProxy methodProxy) throws Throwable try System.out.println(开启事物);Object obj=methodProxy.invoke(targetObject, arg);System.out.println(提交事物);return obj; catch (RuntimeException e) / TODO Auto-generated catch blocke.printStackTrace();System.out.println(回滚事物);finallySystem.out.println(关闭session);return null;测试:public void testCGLIB()CGLIBProxy cglibProxy=new CGLIBProxy(); IPersonDao personDao=(IPersonDao) cglibProxy.createProxyInstance(new PersonDao(); personDao.addPerson(李四);Spring基于xml文件配置方式实现Aop1. 定义一个切面类import org.aspectj.lang.ProceedingJoinPoint;public class XmlInterceptor / 基于spring xml文件配置实现 aoppublic void beforeAdvice()System.out.println(前置通知);public void afterAdvice()System.out.println(后置通知); public void exceptionAdvice() System.out.println(异常通知); public void finallyAdvice() System.out.println(最终通知); public Object aroundAdvice(ProceedingJoinPoint pjp)throws Throwable System.out.println(进入环绕通知); Object result= ceed(); System.out.println(退出环绕通知); return result; 2. src下新建applicationContext_xml.xml文件 !- 采用 cglib 库实现 动态代理 - 测试:public void testXmlAop()ApplicationContext ac=new ClassPathXmlApplicationContext(applicationContext_xml.xml);IPersonDao personDao=(IPersonDao) ac.getBean(personDao);/personDao.addPerson(张三);/personDao.findPersonByPersonId(1);/personDao.deletePerson(1);personDao.updatePerson(李四);Spring基于注解方式实现Aop1. AnnotationInterceptor类:Aspectpublic class AnnotationInterceptor / 基于spring 注解实现 aopPointcut(execution(* com.aop.*.dao.impl.*.add*(.)|execution(* com.aop.*.dao.impl.*.delete*(.) |execution(* com.aop.*.dao.impl.*.update*(.)public void allMethod();Before(allMethod()public void beforeAdvice()System.out.printl
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 单招集合试题及答案
- 药物经济学的实务应用考题及答案
- 系统管理师测试策略与实施方法试题及答案
- 心理咨询师考试的个案研究分析试题及答案
- 激光技术规范与标志试题及答案
- 文化产业管理证书考试精髓试题及答案
- 司法考试训练试题及答案
- 深入分析2024年专利代理人考试的知识架构试题及答案
- 如何应对2025年乡村全科考试坎坷试题及答案
- 药物临床使用的伦理与法律问题试题及答案
- 人民音乐出版社六年级下册音乐教案(全册)
- 药物临床试验概述课件(PPT 23页)
- HP系列圆锥破碎机常见故障
- 安徽中医药大学专升本(语文)科目考试题库(含历年重点题)
- 等离子体光谱诊断实验报告
- COMMERCIAL INVOICE 商业发票
- 永磁吸盘使用方法及安全事项
- 企业计算机基础培训课件
- 哈萨克斯坦2050战略总统国情咨文(中文版)
- 复摆鄂式破碎机
- 接待手册(范本)
评论
0/150
提交评论