![課程筆記06框架it教程spring5講義_第1頁](http://file4.renrendoc.com/view/fe32c4ceec1acb75e723c0b59293bb78/fe32c4ceec1acb75e723c0b59293bb781.gif)
![課程筆記06框架it教程spring5講義_第2頁](http://file4.renrendoc.com/view/fe32c4ceec1acb75e723c0b59293bb78/fe32c4ceec1acb75e723c0b59293bb782.gif)
![課程筆記06框架it教程spring5講義_第3頁](http://file4.renrendoc.com/view/fe32c4ceec1acb75e723c0b59293bb78/fe32c4ceec1acb75e723c0b59293bb783.gif)
![課程筆記06框架it教程spring5講義_第4頁](http://file4.renrendoc.com/view/fe32c4ceec1acb75e723c0b59293bb78/fe32c4ceec1acb75e723c0b59293bb784.gif)
![課程筆記06框架it教程spring5講義_第5頁](http://file4.renrendoc.com/view/fe32c4ceec1acb75e723c0b59293bb78/fe32c4ceec1acb75e723c0b59293bb785.gif)
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
IoCXMLIoCXMLDIIoCSpringSpringAOPSpringAOPXMLSpringSpringJDBCSpringSpringMybatisSpring什么是Spring:SpringSpringFramework(spring框架)為什么學(xué)習springframework:jarjarSpring概念介 SpringAOP:AspectOrientedProgramming,面向切面編程。在不修改目標對象的源代碼情況下,增強IoC容器中Bean的功能。DI:DependencyInjection,依賴注入。SpringBean態(tài)的將依賴對象注入到Bean組件中?。pringIoC******SpringIoCSpringIoCIoCIoC******IoCSpringBean了Bean實例)實現(xiàn)了BeanFactory***BeanFactory工廠(SpringBeanBeanFactoryBean***其實通過源碼分析,不管是BeanFactory還是ApplicationContext,其實最終的底層BeanFactory都是DefaultListableBeanFactoryApplicationContext和BeanFactory***BeanFactory***BeanFactory延遲加載getBeanBean***ApplicationContext是加載完applicationContext.xml時,就創(chuàng)建具體的WebIoC ApplicationContextApplicationContextcontextnewClassPathXmlApplicationContext(xmlServletContextListener接口,該接口的描述請見下面《三類八種器》Spring容器(DefaultListableBeanFactory)。*創(chuàng)建:第一次*銷毀:調(diào)用invalidate();關(guān)閉;過 和web.xmlWebSpringconfigureAndRefreshWebApplicationContext方法中調(diào)用最終初始化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.}catchcatch ceptionex)if(logger.isWarnEnabled())logger.warn("Exceptionencounteredduringcontextinitialization-+"cancellingrefreshattempt:"+}//Destroyalreadycreatedsingletonstoavoiddanglingresources.//Reset'active'flag.//Propagateexceptiontothrow}finally//ResetcommonintrospectioncachesinSpring'score,since//mightnoteverneedmetadataforsingletonbeansanymore...}}}SpringIoCXML POM<project<project"" 組件中的4個依賴--><!--單元測試Junit<!--配置Maven的JDK編譯級別--> <?xml<?xmlversion="1.0"encoding="UTF-<beansxmlns="""在在Spring的XML配置文件中配置一個最終會被加載為一個***UserServiceSpringIoC***SpringIoCUserServiceXMLbean詳***用于配置對象讓spring來創(chuàng)建的。***class:指定類的全限定類名。用于反射創(chuàng)建對象。默認情況下調(diào)用無參構(gòu)造函數(shù):prototyperequest:WEB項目中,Spring創(chuàng)建一個Bean的對象,將對象存入到request域中.session:WEB項目中,Spring創(chuàng)建一個Bean的對象,將對象存入到session域中.global :WEB項目中,應(yīng)用在Portlet環(huán)境.如果沒有Portlet環(huán)globalSession相當于指定 *對 :當對象長時間不用時,被java的bean***如果bean<beanid="userService"*publicclassStaticFactorypublicstaticUserServicereturnnew}}<!--此種方式是:<!--此種方式是:使用StaticFactory類中的靜態(tài)方法createUserService創(chuàng)建對象,并存入spring容器id屬性:指定bean的id,用于從容器中獲取class屬性:指定靜態(tài)工廠的全限定類名factory-method<beanid="userService"class="com.kkb.spring.factory.StaticFactory"factory-publicclassInstanceFactorypublicUserServicereturnnew}}}<!--此種方式是:***先把工廠的創(chuàng)建交給spring來管理。***然后在使用工廠的bean來調(diào)用里面的方法factory-bean屬性:用于指定實例工廠bean的idfactory-method SpringDI***屬性分為:簡單類型(8String)的屬性、POJO***依賴注入:DependencyInjection。它是spring框架ioc的具體實現(xiàn)。層的方法。那這種業(yè)務(wù)層和持久層的依賴關(guān)系,在使用spring之后,就讓spring來publicpublicclassUserServiceImplimplementsUserServiceprivateintprivateStringpublicUserServiceImpl(intid,Stringname)this.id==}publicvoidsaveUser() }}<!--使用構(gòu)造函數(shù)的方式,給<!--使用構(gòu)造函數(shù)的方式,給service***value:它能賦的值是基本數(shù)據(jù)類型和String類型***ref:它能賦的值是其他bean的<beanid="userService"<constructor-argname="name"value="zhangsan"></constructor-方法注入***自動裝配方式(注解方式,后面講解):@Autowired@Resource***@Resource:一部分功能是查找實例springBean1.1.步驟一:需要先引入p名稱空間*在 "p:屬性名p:屬性名-ref3.步驟三:測試*<bean""p:pname基于簡單類型<bean<beanid="userService"<propertyname="id"<propertyname="name"類型ref就是reference的縮寫,是的意思<bean<beanid="userService"<beanid="userDao"1.1.List<beanid="collectionBean"<propertyvaluePOJO<property//如果集合內(nèi)是簡單類型,使用value ,如果是POJO類型,則使<property<entry 2"<entry<entrykey<entrykey4.Properties<property<prop<propSpringIoCDI******學(xué)習基于注解的IoC配置,大家腦海里首先得有一個認知,即注解配置和xml配置***spring的xml配置內(nèi)容改為使用IoC相當于:<beanid=""把資源讓spring來管理。相當于在xml中配置一個beanvalue:指定bean的id如果不指定如果不指定value屬性,默認bean的id是當前類的類名。首字母小寫注解***細節(jié):如果注解中有且只有一個屬性要賦值時,且名稱是value,value在賦值是可以相當于:<propertyname***nullrequired性為false,如:@Autowired(required=false)******在自動按照類型注入的基礎(chǔ)之上,再按照Bean的id注入。***它在給字段注入時不能獨立使用,必須和@Autowire一起使用;但是給方法參數(shù)注入***J2EE***name找不到與名稱匹配的bean時才按照類型進行裝配。推薦使用@ResourceJ2EEspring相當于:<propertyname=""@Value(“${name}”)//namepropertieskeyprivateStringname;相當于相當于<beanid=""class指定bean的作用范圍。取值:singletonprototyperequestsession相當于:相當于:<beanid=""class=""init-method=""destroy-method=""/>和關(guān)于注解和XML配置簡單 ***XML的優(yōu)勢:***Spring管理Bean方式的比較:Spring不開spring的xml配置文件,那么能不能不寫這個applicationContext.xml,所有 非自定義的Bean(比如:SqlSessionFactoryBasicDataSource<beanid="sqlSessionFactory"<propertyname="dataSource">>XMLApplicationContextcontextnew***Spring3.0,@Configuration配置類,可替換xml******配置類內(nèi)部包含有一個或多個被@Bean注解的方法,這些方法將會被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext類進行掃描,并用于構(gòu)建bean定義,初始化Spring容器。屬性示例代碼publicclassSpringConfigurationpublicSpringConfiguration(){}}***bean,比如DruidDataSource、***name:給當前@Bean注解方法創(chuàng)建的對象指定一個名稱(即bean的id) 注解默認作用域為單例 作用域,可通過publicclassSpringConfigurationpublic}publicUserService}}}}publicvoidsaveUser() }publicclassUserServiceImplimplementsUserServicepublicUserServiceuserService(){returnnewUserServiceImpl(1,"}}publicclassSpringConfigurationpublicSpringConfiguration(){}***相當于 publicclassJdbcConfig{privateStringdriver;privateStringurl;privateStringusername;privateStringpassword;publicDataSourcecreateDataSource()trytryComboPooledDataSourceds=newComboPooledDataSource();ds.setDriverClass(driver);returnds;}catch(Exceptione)thrownew}}}之前使用XML配置的時候是如何解決publicclass}@ComponentScan(basePackages="com.kkb.spring")@Import({JdbcConfig.class})publicclassSpringConfiguration}***spring配置文件中的ApplicationContextcontext=ApplicationContextcontext=newUserServiceservice=context.getBean(UserService.class);應(yīng)用Spring分模塊開發(fā)***表現(xiàn)層:spring***業(yè)務(wù)層:springBean,***持久層:spring配置文件,只想管理持久層的Bean,并且還有需要管理數(shù)據(jù)源的個spring配置文件。***另一種就是:定義一個import.xml文件,通過import將其他多個spring配置文件導(dǎo)入到該文件中,tomcat啟動時只需要加載import.xml就可以。IoCDIIoC*********Spring容器(IoC***Spring(如何創(chuàng)建BeanDI類IoCDI***注解+XMLSpringApplicationContextcontextnewClassPathXmlApplicationContext("applicationContext.xml");UserServiceservice1=context.getBean(UserService.class);springJunit給我們***這時,我們需要依靠spring配置文件(***Spring***Spring第三步:通過@ContextConfiguration注解,指定spring運行器需要的配置文件路SpringAOPAOP*AOP,制定了一套規(guī)范.SpringAOP**AOP是OOPSpring*利用AOPAOP采取橫向抽取機制,取代了傳統(tǒng)縱向繼承體系重復(fù)性代碼(性能監(jiān)視、事務(wù)管*AOP --所謂連接點是指那些2PointcutJoinpoint33.Advice4.Introduction(在不修改類代碼的前提下,.()類.AOP實現(xiàn)之AspectJ(了解***AspectJ***AspectJjavaAOPjavaAOP(一般在編譯期進行),讓java代碼具有AspectJ的AOP功能(當然需要特殊的編譯器)***AspectJAOP(CGLIB(底層通過繼承實現(xiàn)),SpringAOPAspectJacjjavacaspectclassjava編譯時織入,即先編譯aspect類再編譯目標類。SpringAOP***Spring***SpringAOP 技術(shù)的實現(xiàn)方式有兩種:基于接口的JDK和基于繼承的CGLib動態(tài)。JDK使 使用JDK的方式生 對@authorpublicclass UtilspublicstaticUserService (finalUserServiceservice)//使 對 newInvocationHandler(){throwsThrowable
publicObject ,Methodmethod,Object[]//開啟事}
//提交事//讓service類的save或者update下returnmethod.invoke(service,////返 對 }}CGLib2.編寫相關(guān)的代碼publicstaticUserServiceget//創(chuàng)建CGLIB的Enhancerenhancer=new//設(shè)置父//設(shè)置回調(diào)函enhancer.setCallback(newMethodInterceptor(){publicObjectintercept(Objectobj,Methodmethod,Object[]args,Methodmethod)throwsThrowable{//記錄日}returnmethod.invokeSuper(obj,}//生成對UserService=(UserService)return}SpringAOPSpringAOP******a、開發(fā)階段(我們做的***把公用代碼抽取出來,制作成通知。(開發(fā)階段最后再做):AOP切入點與通知間的關(guān)系,即切面。:AOP***b、運行階段(Spring框架完成的***Spring框架springIoCAspectJXML<!--基于<!--基于AspectJ的aop依賴-->springIoCAOP切面execution**execution:**修飾符:可省略**返回值類型:必須要,但是可以使用***包名:****包名可以使用*代替,多級包名可以使用多個***如果想省略中間的包名可以使用..**類名**可以使用***也可以寫成**方法名:**也可以使用***也可以寫成****參數(shù):**參數(shù)使用***"***配置文件:<aop:after-returningmethod="afterReturning"pointcut-"***配置文件:<aop:after-throwingmethod="afterThrowing"pointcut- AOP publicclassSpringConfiguration}SpringSpringJDBCJdbcTemte類的使publicvoid//創(chuàng)建連接池,先使用Spring接DriverManagerDataSourcedataSource=newDriverManagerDataSource();dataSource.setUrl("jdbc:mysql:///spring");//創(chuàng)建模板類JdbcTemtejdbcTemte=newJdbcTem te.update("insertintot_accountvaluesnull}Spring管理JdbcTem**步驟一:Spring<propertyname="url"<propertyname="username"<propertyname="password"<bean te" <propertyname="dataSource"publicclassDemo2{ privateJdbcTem tejdbcTem publicvoid te.update("insertintot_accountvaluesnull}}Spring管理第DBCP*先引入DBCP2jar**maven環(huán)境,需要填寫GAV*編寫配置文件<beanid="dataSource" <propertyname="username"<propertyname="password"*先引入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}//刪除操publicpublicvoid 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開發(fā)之WEBjarIOC6AOP4C3P01JDBC2JUnit<beanid="dataSource" <propertyname="driverClass"<propertyname="user"<propertyname="password"<beanid="accountService"<beanid="accountDao"步驟五:在業(yè)務(wù)層注入DAO,在DAOJDBC(強調(diào):簡化開發(fā),以后類<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+?wher
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 加工安裝服務(wù)合同范本
- 別墅家具購買合同范本
- 公司舊車銷售合同范例
- 乙方工地材料合同范例
- 養(yǎng)生館共享店鋪合同范例
- 電源防雷插座板行業(yè)深度研究報告
- 中國電動拉鉚槍項目投資可行性研究報告
- led設(shè)備購買合同范本
- 制種水稻合同范本
- 公司外聘員工合同范例
- 2023年上海青浦區(qū)區(qū)管企業(yè)統(tǒng)一招考聘用筆試題庫含答案解析
- 2023版押品考試題庫必考點含答案
- 植物之歌觀后感
- 空氣能熱泵安裝示意圖
- 建筑工程施工質(zhì)量驗收規(guī)范檢驗批填寫全套表格示范填寫與說明
- 2020年中秋國慶假日文化旅游市場安全生產(chǎn)檢查表
- 昆明天大礦業(yè)有限公司尋甸縣金源磷礦老廠箐-小凹子礦段(擬設(shè))采礦權(quán)出讓收益評估報告
- 心有榜樣行有力量 -從冬奧冠軍徐夢桃身上感受青春奮斗初中主題班會
- GB/T 3860-1995文獻敘詞標引規(guī)則
- 七年級英語下冊閱讀理解10篇
- 設(shè)計質(zhì)量、進度保證措施
評論
0/150
提交評論