




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
IoCXMLIoCXMLDIIoCSpringSpringAOPSpringAOPXMLSpringSpringJDBCSpringSpringMybatisSpring什么是Spring:SpringSpringFramework(spring框架)为什么学习springframework:jarjarSpring概念介 SpringAOP:AspectOrientedProgramming,面向切面编程。在不修改目标对象的源代码情况下,增强IoC容器中Bean的功能。DI:DependencyInjection,依赖注入。SpringBean态的将依赖对象注入到Bean组件中!!SpringIoC******SpringIoCSpringIoCIoCIoC***所谓的***所谓的IoC容器就是指的Spring中Bean工厂里面的 了Bean实例)实现了BeanFactory***BeanFactory工厂(SpringBeanBeanFactoryBean***其实通过源码分析,不管是BeanFactory还是ApplicationContext,其实最终的底层BeanFactory都是DefaultListableBeanFactoryApplicationContext和BeanFactory***BeanFactory***BeanFactory延迟加载getBeanBean***ApplicationContext是加载完applicationContext.xml时,就创建具体的WebIoC ApplicationContextApplicationContextcontextnewClassPathXmlApplicationContext(xmlServletContextListener接口,该接口的描述请见下面《三类八种器》Spring容器(DefaultListableBeanFactory)。*创建:第一次*销毁:调用invalidate();关闭;过 和web.xmlWebSpringconfigureAndRefreshWebApplicationContext方法中调用最终初始化Bean的refresh源码来源 publicvoidrefresh()throws //Preparethiscontextforrefreshing. lthesubclasstorefreshtheinternalbeanfactory.ConfigurableListableBeanFactorybeanFactory=obtainFreshBeanFactory();//Preparethebeanfactoryforuseinthiscontext.try//Allowspost-processingofthebeanfactoryincontextsubclasses. //Invokefactoryprocessorsregisteredasbeansinthecontext.//Registerbeanprocessorsthatinterceptbeancreation.//Initializemessagesourceforthiscontext.//Initializeeventmulticasterforthiscontext.//Initializeotherspecialbeansinspecificcontextsubclasses.//Checkforlistenerbeansandregisterthem.//Instantiateallremaining(non-lazy-init)singletons.//Laststep:publishcorrespondingevent.}catch ceptionex)if(logger.isWarnEnabled())logger.warn("Exceptionencounteredduringcontextinitialization-+"cancellingrefreshattempt:"+}//Destroyalreadycreatedsingletonstoavoiddanglingresources.//Reset'active'flag.//Propagateexceptiontothrow}finally//ResetcommonintrospectioncachesinSpring'score,since//mightnoteverneedmetadataforsingletonbeansanymore...}}}SpringIoCXML POM<projectxmlns=xmlns:xsi=xsi:schemaLocation=<!--spring组件中的4个依赖--<!--单元测试Junit<!--配置Maven的JDK编译级别--> <?xmlversion="1.0"encoding="UTF-<beansxmlns="在Spring的XML配置文件中配置一个bean,该最终会被加载为一XMLbean详 ***用于配置对象让spring来创建的。 ***classsingletonprototyperequest:WEB项目中,Spring创建一个Bean的对象,将对象存入到request域中.session:WEB项目中,Spring创建一个Bean的对象,将对象存入到sessionsession域中. globalsession :WEB项目中,应用在Portlet环境.如果没有Portlet环境那么globalSession相当于session.。:当对象长时间不用时,被java的bean***如果bean<beanid="userService"*publicclassStaticFactorypublicstaticUserServicereturnnew}}<!--此种方式是:<!--此种方式是:使用StaticFactory类中的静态方法createUserService创建对象,并存入spring容器id属性:指定bean的id,用于从容器中获取class属性:指定静态工厂的全限定类名factory-method<beanid="userService"class="com.kkb.spring.factory.StaticFactory"factory-publicclassInstanceFactorypublicUserServicereturnnew}}}<!--此种方式是:***先把工厂的创建交给spring来管理。***然后在使用工厂的bean来调用里面的方法factory-bean属性:用于指定实例工厂bean的idfactory-method SpringDI***依赖注入:DependencyInjection。它是spring框架ioc层的方法。那这种业务层和持久层的依赖关系,在使用spring之后,就让spring来publicclassUserServiceImplimplementsUserServiceprivateintprivateStringpublicUserServiceImpl(intid,Stringname)this.id==}publicvoidsaveUser() }}service***value:它能赋的值是基本数据类型和String类型***ref:它能赋的值是其他bean的<beanid="userService"<constructor-argname="name"value="zhangsan"></constructor-set方法注入set***自动装配方式(注解方式,后面讲解):@Autowired@Resource***@Resource:一部分功能是查找实例springBean1.1.步骤一:需要先引入p名称空间*在 "p:属性名=""p:属性名-ref3.步骤三:测试*<bean"""基于<bean<beanid="userService"<bean<beanid="userService"<beanid="userDao"<beanid="collectionBean"<property<property<property<entry 2"<entry "<entrykey<property<prop<propSpringIoCDI***学习基于注解的IoC配置,大家脑海里首先得有一个认知,即注解配置和xml配置***spring的xml配置内容改为使用IoC相当于:<beanid=""把资源让spring来管理。相当于在xml中配置一个beanvalue:指定bean的id如果不指定value属性,默认bean的id注解***细节:如果注解中有且只有一个属性要赋值时,且名称是value,value在赋值是可以相当于:<propertyname性为false,如:@Autowired(required=false)******在自动按照类型注入的基础之上,再按照Bean的id注入。***它在给字段注入时不能独立使用,必须和@Autowire一起使用;但是给方法参数注入***J2EE***name找不到与名称匹配的bean时才按照类型进行装配。推荐使用@ResourceJ2EEspring相当于:<propertyname=""privateString相当于相当于<beanid=""class指定bean的作用范围。取值:singletonprototyperequestsession相当于:相当于:<beanid=""class=""init-method=""destroy-method=""/>和关于注解和XML配置简单 ***XML的优势:***Spring管理Bean方式的比较:Spring***IoC不开spring的xml配置文件,那么能不能不写这个applicationContext.xml,所有 非自定义的Bean(比如:SqlSessionFactoryBasicDataSource<beanid="sqlSessionFactory"<propertyname="dataSource">>XMLApplicationContextcontextnew***Spring3.0,@Configuration配置类,可替换xml******配置类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。属性示例代码publicclassSpringConfigurationpublicSpringConfiguration(){}}***bean,比如DruidDataSource、***name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id) 注解默认作用域为单例 作用域,可通过publicclassSpringConfigurationpublic}publicUserServicereturnnew}}和publicclassUserServiceImplimplementsUserServicepublicvoidsaveUser() }}publicclassSpringConfiguration{publicSpringConfiguration(){} publicUserServiceuserService() returnnewUserServiceImpl(1," }publicclassJdbcConfig{privateStringdriver;privateStringurl;privateStringusername;privateStringpassword;publicDataSourcecreateDataSource()tryComboPooledDataSourceds=newComboPooledDataSource();ds.setDriverClass(driver);returnds;}catch(Exceptione)thrownew}}}之前使用XML配置的时候是如何解决***spring配置文件中的import@ComponentScan(basePackages="com.kkb.spring")@Import({JdbcConfig.class})publicclassSpringConfiguration}publicclass}ApplicationContextcontext=newUserServiceservice=context.getBean(UserService.class);应用IoCDISpringApplicationContextcontextnewClassPathXmlApplicationContext("applicationContext.xml");UserServiceservice1=context.getBean(UserService.class);springJunit给我们***这时,我们需要依靠spring配置文件(***Spring***Spring第三步:通过@ContextConfiguration注解,指定spring运行器需要的配置文件路Spring分模块开发***表现层:spring***业务层:springBean,***持久层:spring配置文件,只想管理持久层的Bean,并且还有需要管理数据源的***持久层:spring配置文件,只想管理持久层的Bean,并且还有需要管理数据源的个spring配置文件。***另一种就是:定义一个import.xml文件,通过import将其他多个spring配置文件导入到该文件中,tomcat启动时只需要加载import.xml就可以。SpringAOPAOP*AOP,制定了一套规范.SpringAOP*是*利用AOPAOP采取横向抽取机制,取代了传统纵向继承体系重复性代码(性能监视、事务管AOP --所谓连接点是指那些 2.PointcutJoinpoint3.Advice--所谓通知是指到Joinpoint4.Introduction(引介)--引介是一种特殊在不修改类代码的前提下,5.Target6.Weaving()类8.AspectAOP实现之AspectJ(了解***AspectJ***AspectJjavaAOPjavaAOP(***AspectJAOP简单理解为aspect(切面)应用到目标函数(类)的过程。技术完成JavaJDK(CGLIB(底层通过继承实现),SpringAOPAspectJacjjavacaspectclassjava编译时织入,即先编译aspect类再编译目标类。SpringAOP***Spring***SpringAOP技术的实现方式有两种:基于接口的JDK和基于继承的CGLib动态。JDK使用类来生成对象的一些代码如下使用JDK的方式生成对@authorpublicclassMyUtilspublicstaticUserServiceget(finalUserServiceservice)//使用类生成对UserService(UserService).newInstance(newInvocationHandler(){//对象方法一执行,invoke方法就会执行一publicObjectinvoke(Object,Methodmethod,Object[]throwsThrowable//开启事}//提交事//让service类的save或者update下returnmethod.invoke(service,}//返回对return}}CGLib生子对象2.编写相关的代码publicstaticUserService//创建 Enhancerenhancer=new//设置父//设置回调函enhancer.setCallback(newMethodInterceptor(){publicObjectintercept(Objectobj,Methodmethod,Object[]args, )throwsThrowable{//记录日}return }//生 对 =(UserService)enhancer.create(); }SpringAOPspringAOP******a、开发阶段(我们做的***把公用代码抽取出来,制作成通知。(开发阶段最后再做):AOP切入点与通知间的关系,即切面。:AOP***b、运行阶段(Spring框架完成的***Spring框架springIoCAspectJXML<!--基于<!--基于AspectJ的aop依赖-->springIoCAOP切面execution(**execution:**修饰符:可省略**返回值类型:必须要,但是可以使用***包名:****包名可以使用*代替,多级包名可以使用多个*******类名**可以使用***也可以写成**方法名:**也可以使用***也可以写成**参数:**参数使用***"***配置文件:<aop:after-returningmethod="afterReturning"pointcut-"***配置文件:<aop:after-throwingmethod="afterThrowing"pointcut- AOP publicclassSpringConfiguration}SpringSpringJDBCJdbcTemte类的使publicvoid//创建连接池,先使用Spring接DriverManagerDataSourcedataSource=newDriverManagerDataSource();dataSource.setUrl("jdbc:mysql:///spring");//创建模板类JdbcTemtejdbcTemte=newJdbcTem te.update("insertintot_accountvaluesnull}Spring管理JdbcTem**步骤一:Spring<propertyname="url"<propertyname="username"<propertyname="password"*步骤二:Spring<bean<bean te" <propertyname="dataSource"*publicclassDemo2{ privateJdbcTem tejdbcTem publicvoid te.update("insertintot_accountvaluesnull}}Spring管理第DBCP*先引入DBCP2jar**maven环境,需要填写GAV*编写配置文件<beanid="dataSource" <propertyname="username"<propertyname="password"C3P0**先引入C3P0jar**<beanid="dataSource"<propertyname="driverClass"<propertyname="jdbcUrl"<propertyname="user"<propertyname="password"使用JdbcTemte完成增删改查操publicclassSpringDemo{ privateJdbcTem tejdbcTem //插入操publicvoid te.update("insertintoaccountvalues(null,?,?)", }//修改操publicvoid te.update("updateaccountsetname=?,moneywhereid}//删除操publicvoid te.update("deletefromaccountwhereid=?",}publicvoidAccountaccount=jdbcTem te.queryForObject("select*fromaccountwhereid=?",newBeanMapper(),1);}publicvoidList<Account>list=jdbcTem te.query("select*fromt_account",newBeanMapper());for(Accountaccount:list){}}}classBeanMapperimplementspublicAccountmapRow(ResultSetrs,intarg1)throwsSQLException{Accountaccount=newAccount();returnaccount;}}springdao开发之WEBjarIOC6AOP4C3P01JDBC2JUnit<beanid="dataSource" <propertyname="driverClass"<propertyname="user"<propertyname="password"<beanid="accountService"<beanid="accountDao"步骤五:在业务层注入DAO,在DAOJDBC(强调:简化开发,以后类<beanid="accountService"<propertyname="accountDao"<beanid="accountDao"<propertyname="dataSource"publicclassAccountDaoImplextendsJdbcDaoSupportimplementsAccountDao{publicvoidoutMoney(Stringout,doublemoney){ te().update("updatet_accountsetmoney=money=?wherename=?",money,out);}publicvoidinMoney(Stringin,doublemoney) te().update("updatet_accountsetmoney=money+?wheren
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 渗透市场意识的2024年国际商业美术设计师考试试题及答案
- 六上生命教育试题及答案
- 2024年纺织设计行业新趋势试题及答案
- 助理广告师考试重点内容概述试题及答案
- 分析纺织品市场趋势对检验的影响因素试题及答案
- 2024年纺织对接新技术试题及答案
- 智能家居知识试题及答案
- 极致提升广告设计师能力试题及答案
- 2024年纺织品检验员证书考试深度分析试题及答案
- 意外伤害试题及答案库
- 污水处理厂设备运行的管理及维护措施
- 1-江苏省冶金等工贸企业安全生产标准化运行质量审计评分表-
- 弘扬航天精神拥抱星辰大海!课件高一上学期载人航天主题班会
- 《excel数据分析》课件
- DB1310-T 223-2020 小麦节水绿色丰产栽培技术规程
- 小学六年级科学(人教版)《各种各样的自然资源》-教学设计、课后练习、学习任务单
- 215kWh工商业液冷储能电池一体柜用户手册
- 燃气安全事故处理及应急
- 汽车发动机构造与维修课件 第六章 燃油供给系
- 可再生能源预测技术研究
- 2024-2030年中国耐火材料行业供需分析及发展前景研究报告
评论
0/150
提交评论