Spring框架教学课件ppt.ppt

上传人:牧羊曲112 文档编号:5449077 上传时间:2023-07-08 格式:PPT 页数:95 大小:1.73MB
返回 下载 相关 举报
Spring框架教学课件ppt.ppt_第1页
第1页 / 共95页
Spring框架教学课件ppt.ppt_第2页
第2页 / 共95页
Spring框架教学课件ppt.ppt_第3页
第3页 / 共95页
Spring框架教学课件ppt.ppt_第4页
第4页 / 共95页
Spring框架教学课件ppt.ppt_第5页
第5页 / 共95页
点击查看更多>>
资源描述

《Spring框架教学课件ppt.ppt》由会员分享,可在线阅读,更多相关《Spring框架教学课件ppt.ppt(95页珍藏版)》请在三一办公上搜索。

1、Spring企业开发,广西柳州创景软件人才实训中心,Spring是什么,Spring是一个开源的控制反转(Inversion of Control,IoC)和面向切面(AOP)的容器框架.它的主要目的是简化企业开发.,IOC 控制反转,public class PersonService/服务层 private PersonDao personDao=new PersonDaoBean();public void save(Person person)/保存一个对象 personDao.save(person);PersonDaoBean 是在应用内部创建及维护的(在PersonService

2、 类中new出来的)。所谓控制反转就是应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护是由外部容器负责的。这样控制权就由应用转移到了外部容器,控制权的转移就是所谓反转。,依赖注入(Dependency Injection),当我们把依赖对象交给外部容器负责创建,那么PersonService 类可以改成如下:public class PersonService private PersonDao personDao;/通过构造器参数,让容器把创建好的依赖对象注入进PersonService,当然也可以使用setter方法进行注入。public PersonService(PersonD

3、ao personDao)this.personDao=personDao;public void save(Person person)personDao.save(person);所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中。,为何要使用Spring,在项目中引入spring立即可以带来下面的好处降低组件之间的耦合度,实现软件各层之间的解耦。可以使用容器提供的众多服务,如:事务管理服务、消息服务等等。当我们使用容器管理事务时,开发人员就不再需要手工控制事务.也不需处理复杂的事务传播。容器提供单例模式支持,开发人员不再需要自己编写实现代码。容器提供了AOP技术,利用它

4、很容易实现如权限拦截、运行期监控等功能。容器提供的众多辅作类,使用这些类能够加快应用的开发,如:JdbcTemplate、HibernateTemplate。Spring对于主流的应用框架提供了集成支持,如:集成Hibernate、JPA、Struts等,这样更便于应用的开发。,Controller,Service,DAO,使用Spring的好处,当使用spring时,我们可以使用容器提供的众多服务,如果使用Spring,我们就不再需要手工控制事务,public void savePerson()People people=new People();people.setName(李四);try

5、 session.save(people);mit();catch(HibernateException e)transaction.rollback();e.printStackTrace();,使用Hibernate框架需要手工提交事务,另外,如果使用spring,我们也不需要处理复杂的事务传播行为,public void payment()Bean1.update();/更新金额 Bean2.save();/记录操作日志如果我们不使用Spring,针对下面这两种业务需求,我们该如何做?第1种可能的业务需求:要求Bean1.update()和Bean2.save()在同一个事务中执行。第2

6、种可能的业务需求:要求不管Bean1.update()的事务是否成功,都需要记录操作日志。public class Bean1 public void update()/注意:下面省略了一些代码 Connection conn=null;conn.setAutoCommit(false);Statement.executeUpdate(“update account set amount=?where id=?);public class Bean2 public void save()/注意:下面省略了一些代码 Connection conn=null;conn.setAutoCommit(

7、false);Statement.executeUpdate(“insert into Log(content)values(?);,使用Spring,不再需要我们处理复杂的事务传播行为,使用Spring,我们只需要通过声明式的事务属性配置就可以轻松地实现这两种业务需求1.要求Bean1.update()和Bean2.save()的在同一个事务中执行2.要求不管Bean1.update()的事务是否成功,都需要记录日志。Transactional(propagation=Propagation.Required)public void payment()Bean1.update();/更新金额

8、 Bean2.save();/记录日志 public class Bean1 Transactional(propagation=Propagation.Required)public void update()executeUpdate(“update account set amount=?where id=?);public class Bean2 Transactional(propagation=Propagation.RequiresNew)public void save()executeUpdate(“insert into Log(content)values(?);,轻量级

9、与重量级概念的划分,经常会有同学问到spring属于轻量级框架,还是重量框架?其实划分一个应用是否属于轻量级还是重量级,主要看它使用了多少服务.使用的服务越多,容器要为普通java对象做的工作就越多,必然会影响到应用的发布时间或者是运行性能.对于spring容器,它提供了很多服务,但这些服务并不是默认为应用打开的,应用需要某种服务,还需要指明使用该服务,如果应用使用的服务很少,如:只使用了spring核心服务,那么我们可以认为此时应用属于轻量级的,如果应用使用了spring提供的大部分服务,这时应用就属于重量级。目前EJB容器就因为它默认为应用提供了EJB规范中所有的功能,所以它属于重量级。,

10、使用Spring需要的jar,到下载spring,然后进行解压缩,在解压目录中找到下面jar文件,拷贝到类路径下distspring.jarlibjakarta-commonscommons-logging.jar如果使用了切面编程(AOP),还需要下列jar文件lib/aspectj/aspectjweaver.jar和aspectjrt.jar如果使用了JSR-250中的注解,如Resource/PostConstruct/PreDestroy,还需要下列jar文件libj2eecommon-annotations.jar,本次课程使用的Spring版本是2.5,使用myeclipse添加

11、Spring应用,第一步:创建web工程(其实普通j2se工程也可以),使用myeclipse添加Spring应用,第二步:在web工程中添加Spring框架支持,使用myeclipse添加Spring应用,这里只是简单应用,没有涉及到和其它框架的集成,因此选择前面两个就可以了。,使用myeclipse添加Spring应用,这步的目的是生成Spring配置文件applicationContext.xml文件位置是src,使用myeclipse添加Spring应用,框架添加完成之后的效果,使用myeclipse添加Spring应用,public class UserInfo private In

12、teger id;private String name;private String address;private Integer age;/set and get method,第三步:创建一个实体类;并生成属性对应的set/get方法,使用myeclipse添加Spring应用,第四步:根据左边的实体类属性名称和数据类型在Spring配置文件中配置一个bean;这个bean的id值是userInfoBean这个id属性名称对应的值在applicationContext.xml必须是唯一;不能存在同名;在应用程序中将根据id名称来获取这个bean,使用myeclipse添加Spring应

13、用,/编写测试类,从Spring容器中获取userInfoBeanpackage.chongking;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class BeanUtil public static void main(String args)ApplicationContext context=new ClassPathXmlApplicationContext(a

14、pplicationContext.xml);UserInfo userInfo=(UserInfo)context.getBean(“normalBean);System.out.println(userInfo.getName()+:+userInfo.getAddress();,第五步:编写测试类;从spring容器中根据bean的id获取bean对象userInfoBean是applicationContext.xml配置文件中的bean id属性值,applicationContext.xml,使用eclipse添加Spring应用,使用eclipse开发Spring应用需要自己添加

15、使用到的jar文件和spring配置文件(applicationContext.xml)其它的配置和测试跟使用myeclipse是一样的。在java体系中绝大部分的框架应用所涉及到的引用基本上都是jar文件和配置文件。Jar文件和配置文件有多种渠道可以获取;可以从官方网站上下载;可以使用别人现有的;可以通过其它渠道获取。,spring的配置文件模版,.该配置模版可以从spring的参考手册或spring的例子中得到。配置文件的取名可以任意,文件可以存放在任何目录下,但考虑到通用性,一般放在类路径下。,编写spring配置文件时,不能出现帮助信息,由于spring的schema文件位于网络上,如

16、果机器不能连接到网络,那么在编写配置信息时候就无法出现提示信息,解决方法有两种:1。让机器上网,eclipse会自动从网络上下载schema文件并缓存在硬盘上。2。手动添加schema文件,方法如下:windwos-preferences-myeclipse-files and editors-xml-xmlcatalog点add,在出现的窗口中的Key Type中选择URI,在location中选File system,然后在spring解压目录的dist/resources目录中选择spring-beans-2.5.xsd,回到设置窗口的时候不要急着关闭窗口,应把窗口中的Key Type改

17、为Schema location,Key改为,实例化spring容器,实例化Spring容器常用的两种方式:方法一:在类路径下寻找配置文件来实例化容器ApplicationContext ctx=new ClassPathXmlApplicationContext(new Stringbeans.xml);方法二:在文件系统路径下寻找配置文件来实例化容器ApplicationContext ctx=new FileSystemXmlApplicationContext(new String“d:beans.xml“);Spring的配置文件可以指定多个,可以通过String数组传入。,从spr

18、ing容器中得到bean,当spring容器启动后,因为spring容器可以管理bean对象的创建,销毁等生命周期,所以我们只需从容器直接获取Bean对象就行,而不用编写一句代码来创建bean对象。从容器获取bean对象的代码如下:ApplicationContext ctx=new ClassPathXmlApplicationContext(“beans.xml”);OrderService service=(OrderService)ctx.getBean(personService);,使用dom4j读取spring配置文件,public class ClassPathXmlAppli

19、cationContext private List beanDefines=new ArrayList();public ApplicationContext(String filename)init(filename);private void init(String filename)SAXReader saxReader=new SAXReader();Document document=null;try URL xmlpath=this.getClass().getClassLoader().getResource(filename);document=saxReader.read(

20、xmlpath);Map nsMap=new HashMap();nsMap.put(ns,http:/www.springframework.org/schema/beans);/加入命名空间 XPath xsub=document.createXPath(/ns:beans/ns:bean);/创建beans/bean查询路径 xsub.setNamespaceURIs(nsMap);/设置命名空间 List beans=xsub.selectNodes(document);/获取文档下所有bean节点 for(Element element:beans)String id=element

21、.attributeValue(id);/获取id属性值 String clazz=element.attributeValue(class);/获取class属性值 BeanDefinition beanDefine=new BeanDefinition(id,clazz);beanDefines.add(beanDefine);catch(Exception e)e.printStackTrace();,三种实例化bean的方式-使用类构造器实例化,/实体类设计public class UserInfo private Integer id;private String name;priv

22、ate String address;private Integer age;/构造子public UserInfo()/构造子public UserInfo(Integer id,String name,String address,Integer age)this.id=id;this.name=name;this.address=address;this.age=age;/set and get method,applicationContext.xml配置,/从Spring容器获取Bean测试代码public void getUserInfo()UserInfo userInfo=(U

23、serInfo)context.getBean(normalBean);System.out.println(userInfo.getId()+:+userInfo.getName()+:+userInfo.getAddress();,三种实例化bean的方式-使用静态工厂方法实例化,/工厂类设计public class BeanFactory public static UserInfo factoryDao()return new UserInfo(1,王五,南宁,21);,applicationContext.xml配置,public void staticFactoryBean()/测

24、试代码UserInfo userInfo=(UserInfo)context.getBean(staticFactoryBean);System.out.println(userInfo.getId()+:+userInfo.getName()+:+userInfo.getAddress();,/实体类设计public class UserInfo private Integer id;private String name;private String address;private Integer age;/构造子public UserInfo()/构造子public UserInfo(I

25、nteger id,String name,String address,Integer age)this.id=id;this.name=name;this.address=address;this.age=age;/set and get method,三种实例化bean的方式-使用实例工厂方法实例化,/工厂类设计public class BeanFactory public UserInfo createUserInfo()return new UserInfo(1,王五,南宁,21);,applicationContext.xml配置,/使用实例工厂方法实例化测试public void

26、 instanceFactoryBean()UserInfo userInfo=(UserInfo)context.getBean(instanceFactoryBean);System.out.println(userInfo.getId()+:+userInfo.getName()+:+userInfo.getAddress();,Bean的作用域(scope属性),.singleton 在每个Spring IoC容器中一个bean定义只有一个对象实例。默认情况下会在容器启动时初始化bean,但我们可以指定Bean节点的lazy-init=“true”来延迟初始化bean,这时候,只有第一

27、次获取bean会才初始化bean。如:如果想对所有bean都应用延迟初始化,可以在根节点beans设置default-lazy-init=“true“,如下:可以通过在构造函数中输出信息来跟踪.prototype 每次从容器获取bean都是新的对象。.request.session.global session,request,session,global session是针对web程序而言的,指定Bean的初始化方法和销毁方法,指定Bean的初始化方法和销毁方法,import org.junit.*;import org.springframework.context.support.Abs

28、tractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class BeanUtil AbstractApplicationContext context=null;/Spring容器对象(注意:不是ApplicationContext)Beforepublic void before()System.out.println(before.);context=new ClassPathXmlApplicationContext(applica

29、tionContext.xml);Testpublic void getEmployeeBean()/Employee类中有两个方法:init();和close()Employee employee=(Employee)context.getBean(empBean);System.out.println(employee.getName();Afterpublic void after()context.close();/需要显示调用,注入依赖对象-基本类型对象注入,public class Employee/实体类设计private Integer id;private String na

30、me;private String address;public Employee()System.out.println(不带参数的构造方法.);public Employee(Integer id,String name,String address)System.out.println(带参数构造函数.);this.id=id;this.name=name;this.address=address;/set and get method.,注入依赖对象-构造器注入,applicationContext.xml配置,实体类构造方法public Employee(Integer id,Str

31、ing name,String address)System.out.println(带参数构造函数.);this.id=id;this.name=name;this.address=address;Testpublic void getEmployeeBean()/测试方法 Employee employee=(Employee)context.getBean(empBean);System.out.println(employee.getId()+:+employee.getName()+:+employee.getAddress();,注入依赖对象-注入其它Bean-1,applicat

32、ionContext.xml配置,public class Cpu public void hardwareInfo()System.out.println(AMD 速龙);,Testpublic void getComputer()/测试类 Computer computer=(Computer)context.getBean(computerBean);computer.testCput();,public class Computer private Cpu cpu;/set方法是必须的(set注入)public void setCpu(Cpu cpu)this.cpu=cpu;publ

33、ic Cpu getCpu()return cpu;public void testCput()cpu.hardwareInfo();,注入依赖对象-注入其它Bean-2,applicationContext.xml配置,public class Cpu public void hardwareInfo()System.out.println(AMD 速龙);,Testpublic void getComputer()/测试类 Computer computer=(Computer)context.getBean(computerBean);computer.testCput();,publi

34、c class Computer private Cpu cpu;/set方法是必须的(set注入)public void setCpu(Cpu cpu)this.cpu=cpu;public Cpu getCpu()return cpu;public void testCput()cpu.hardwareInfo();,使用内部bean,但该bean不能被其他bean使用,练习-通过Bean注入模拟计算机组装,/接口设计public interface USB/USB接口信息 public void info(String content);public interface Iprint/打

35、印机接口信息 public void info(String content);,public class Memory/内存类 public void info(String config)System.out.println(内存配置:+config);public class Computer/计算机类 private USB usb;private Iprint print;private Memory memory;public void showHardWareInfo()usb.info(移动硬盘);print.info(彩色打印机);memory.info(金士顿内存条);/省

36、略了set、get方法,applicationContext.xml配置,Testpublic void getComputer()/模拟计算机组装测试方法 Computer computer=(Computer)context.getBean(computerBean);computer.showHardWareInfo();,/接口实现类public class UDisk implements USB public void info(String config)System.out.println(usb接口配置:+config);public class ColorPrint imp

37、lements Iprint public void info(String config)System.out.println(彩色打印机:+config);,集合类型的装配,cjkj set cjkj,Testpublic void getOrder()/测试类 Order order=(Order)context.getBean(order);List lists=order.getLists();for(String s:lists)System.out.println(s);,public class Order private Set sets=new HashSet();priv

38、ate List lists=new ArrayList();private Properties properties=new Properties();private Map maps=new HashMap();./这里省略属性的getter和setter方法,依赖注入,使用构造器注入使用属性setter方法注入使用Field注入(用于注解方式)注入依赖对象可以采用手工装配或自动装配,在实际应用中建议使用手工装配,因为自动装配会产生未知情况,开发人员无法预见最终的装配结果。1.手工装配依赖对象2.自动装配依赖对象,依赖注入-手工装配,手工装配依赖对象,在这种方式中又有两种编程方式1.在x

39、ml配置文件中,通过在bean节点下配置,如/构造器注入(带参构造函数第1个值)/构造器注入(带参构造函数第2个值)/构造器注入(带参构造函数第3个值)/属性setter方法注入2.在java代码中使用Autowired或Resource注解方式进行装配。但我们需要在xml配置文件中配置以下信息:这个配置隐式注册了多个对注释进行解析处理的处理器:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotati

40、onBeanPostProcessor 注:Resource注解在spring安装目录的libj2eecommon-annotations.jar,依赖注入-手工装配,在java代码中使用Autowired或Resource注解方式进行装配,这两个注解的区别是:Autowired 默认按类型装配,Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配。Autowired private PersonDao personDao;/用于字段上 Autowired public void setOrderDao(OrderDao orderDao)/用于属性的setter方法上

41、this.orderDao=orderDao;Autowired注解是按类型装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它required属性为false Autowired(required=false)。如果我们想使用按名称装配,可以结合Qualifier注解一起使用。如下:Autowired Qualifier(personDaoBean)private PersonDao personDao;Resource注解和Autowired一样,也可以标注在字段或属性的setter方法上,但它默认按名称装配。名称可以通过Resource的name属性指定,如果没

42、有指定name属性,当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找依赖对象。Resource(name=“personDaoBean”)private PersonDao personDao;/用于字段上注意:如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时,Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了。,依赖注入-手工装配-注解装配Autowired,public class Computer/计算机类 Autowired private US

43、B usb;Autowired private Iprint print;Autowired private Memory memory;public void showHardWareInfo()usb.info(移动硬盘);print.info(彩色打印机);memory.info(金士顿内存条);/不用再写set、get方法,bean.xml配置-,Testpublic void getComputer()/模拟计算机组装测试方法 Computer computer=(Computer)context.getBean(computerBean);computer.showHardWare

44、Info();,与xml配置文件中配置引用的Bean的区别是:Computer Bean中不用再配置引用的Bean;这是优点;缺点是还是要在spring配置文件中配置uDisk,colorPrint,memory,computerBean这些Bean,依赖注入-手工装配-注解装配Resource,public class Computer private USB usb;private Iprint print;private Memory memory;public void showHardWareInfo()usb.info(移动硬盘);print.info(彩色打印机);memory.

45、info(金士顿内存条);Resource(name=uDisk)public void setUsb(USB usb)this.usb=usb;Resource(name=colorPrint)public void setPrint(Iprint print)this.print=print;Resource(name=memory)public void setMemory(Memory memory)this.memory=memory;/不用再写set、get方法,bean.xml配置-,Testpublic void getComputer()/模拟计算机组装测试方法 Comput

46、er computer=(Computer)context.getBean(computerBean);computer.showHardWareInfo();,与xml配置文件中配置引用的Bean的区别是:Computer Bean中不用再配置引用的Bean;这是优点;缺点是还是要在spring配置文件中配置uDisk,colorPrint,memory,computerBean这些Bean,依赖注入-自动装配依赖对象,对于自动装配,大家了解一下就可以了,实在不推荐大家使用。例子:autowire属性取值如下:byType:按类型装配,可以根据属性的类型,在容器中寻找跟该类型匹配的bean。

47、如果发现多个,那么将会抛出异常。如果没有找到,即属性值为null。byName:按名称装配,可以根据属性的名称,在容器中寻找跟该属性名相同的bean,如果没有找到,即属性值为null。constructor与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常。autodetect:通过bean类的自省机制(introspection)来决定是使用constructor还是byType方式进行自动装配。如果发现默认的构造器,那么将使用byType方式。,通过在classpath自动扫描方式把组件纳入spring容器中管理,

48、前面的例子我们都是使用XML的bean定义来配置组件。在一个稍大的项目中,通常会有上百个组件,如果这些这组件采用xml的bean定义来配置,显然会增加配置文件的体积,查找及维护起来也不太方便。spring2.5为我们引入了组件自动扫描机制,他可以在类路径底下寻找标注了Component、Service、Controller、Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件是一样的。要使用自动扫描机制,我们需要打开以下配置信息:其中base-package为需要扫描的包(含子包)。Service用于标注业务层组件、Contro

49、ller用于标注控制层组件(如struts中的action)、Repository用于标注数据访问组件,即DAO组件。而Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。,自动扫描式注入Bean(优点:配置文件中不用再配置bean),/接口设计public interface USB/USB接口信息 public void info(String content);public interface Iprint/打印机接口信息 public void info(String content);,Component(memory)public class Memor

50、y/内存类 public void info(String config)System.out.println(内存配置:+config);Component(computer)public class Computer/面向接口编程,下面的 组件都是接口,不是类Resource(name=usb)private USB usb;Resource(name=colorPrint)private Iprint print;Resource(name=memory)private Memory memory;public void showHardWareInfo()usb.info(移动硬盘);

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号