spring框架案例學(xué)習(xí)文檔筆記_第1頁(yè)
spring框架案例學(xué)習(xí)文檔筆記_第2頁(yè)
spring框架案例學(xué)習(xí)文檔筆記_第3頁(yè)
spring框架案例學(xué)習(xí)文檔筆記_第4頁(yè)
spring框架案例學(xué)習(xí)文檔筆記_第5頁(yè)
已閱讀5頁(yè),還剩30頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

spring框架案例學(xué)習(xí)文檔筆記spring框架案例學(xué)習(xí)文檔筆記spring框架案例學(xué)習(xí)文檔筆記spring框架案例學(xué)習(xí)文檔筆記編制僅供參考審核批準(zhǔn)生效日期地址:電話:傳真:郵編:Spring–SSH整合學(xué)習(xí)筆記wjt276[2010-05-14]目錄第一課:面向抽象編程 4第二課:Jdom的基本使用 4第三課:模擬Spring功能 5第四課:搭建sping的運(yùn)行環(huán)境 8一、 建立一個(gè)新的項(xiàng)目 8二、 建立spring的配置文件 8三、 引入spring的jar包 8四、 測(cè)試代碼: 8五、 注意接口的使用: 8第五課:IOC(DI)配置及應(yīng)用 9一、 什么是IOC、DI 9二、 編輯xml文件時(shí),沒(méi)有提示 9三、 注入類型(Injectingdependencies) 9(一) setter注入類型SetterInjection 9(二) 構(gòu)造方法ConstructorInjection 10四、 id、name 11五、 簡(jiǎn)單屬性的注入 11六、 Bean的作用范圍scope 12七、 集合注入 12八、 自動(dòng)裝配autowire 13(一) byName 13(二) byType 14(三) 注意 14九、 生命周期 15(一) lazy-init/default-lazy-init 15(二) init-methoddestroy-method不要和prototype一起用(了解) 15第六課:annotation方式Spring 16一、 開(kāi)始使用annotation配置Spring 16二、 @Autowired、@Qualifier 16(一) @Autowired 16(二) @Qualifier 17三、 @Resource(重要、推薦) 17(一) JSR-250 17(二) @Resource 17四、 @Componet 18五、 @Scope、@PostConstruct、@PreDestroy 19六、 注解對(duì)應(yīng)的jar包 19第七課:AOP(面向切面編程) 19一、 AOP概念 19二、 利用動(dòng)態(tài)代理實(shí)現(xiàn)面向切面編程 20第八課:SpringAOP配置選項(xiàng) 21一、 AOP配置annotation方式 21(一) 搭建annotation開(kāi)發(fā)環(huán)境 21(二) aspectJ類庫(kù) 22(三) AOP的annotation實(shí)例 22(四) AspectJ的專業(yè)術(shù)語(yǔ) 23(五) 織入點(diǎn)語(yǔ)法 23(六) Advice 24(七) Pointcut 26(八) annotatin方式的AOP實(shí)例 26二、 AOP配置xml方式 27三、 AOP實(shí)現(xiàn)動(dòng)態(tài)代理注意 28第九課:DataSource 28一、 Sping配置數(shù)據(jù)源: 28二、 注入使用 29三、 29第十課Spring整合Hiberante3 30一、 Spring配置hibernate3的SessionFactory 30(一) xml形式的SessionFactory 30(二) annotation注解方式的SessionFactory 30二、 引入hibernate所需要使用的jar 31(一) 基本jar 31(二) 加入annotation功能的jar包 31(三) 搭建日志環(huán)境并配置顯示DDL語(yǔ)句jar包 31三、 Spring整合hibernate3事務(wù) 31(一) Annotation注解方式配置事務(wù)管理 31(二) Spring事務(wù)選項(xiàng) 35(三) XML文件形式配置Spring事務(wù)管理 37四、 HibernateTemplate 38(一) HibernateTemplate 38(二) HibernateDaoSupport 39第十一課:Spring整合-SSH 40一、 第一步:加入jar包(需要的jar包列表) 40二、 第二步:首先整合Spring+Hibernate 41三、 第三步:再來(lái)整合Struts2 41四、 struts的讀常量: 43第十二課:DTO、VO 43一、 DTO 43二、 VO 43第十二課:SSH整合存在的問(wèn)題 43一、 Jsp中訪問(wèn)Session時(shí),Session已經(jīng)關(guān)閉 43二、 如果不配置事務(wù),openSessionView出現(xiàn)異常 44三、 中文亂碼問(wèn)題: 44第十三課:SSH整合的jar包 45一、 Struts2 45二、 45三、 Spring 46

第一課:面向抽象編程原來(lái)什么類都是寫死的,現(xiàn)在是先建立一個(gè)大的標(biāo)準(zhǔn),然后再各個(gè)實(shí)體類來(lái)實(shí)現(xiàn)他們的功能,然后在調(diào)用的時(shí)候,使用這個(gè)標(biāo)準(zhǔn)調(diào)用,這樣,你們那個(gè)來(lái)都可以被調(diào)用。實(shí)例:User實(shí)體類publicclassUser{ privateStringusername; privateStringpassword; publicStringgetUsername(){ returnusername; } publicvoidsetUsername(Stringusername){=username;} publicStringgetPassword(){returnpassword; } publicvoidsetPassword(Stringpassword){ =password; }}UserDao接口publicinterfaceUserDao{ publicvoidsave(Useru);}UserDao的實(shí)現(xiàn)UserDaoImplpublicclassUserDaoImplimplementsUserDao{ @Override publicvoidsave(Useru){ "usersave..."); }}User管理類publicclassUserService{ ewInstance(); (id,o); } } publicObjectgetBean(Stringname){ return(name); }}測(cè)試:BeanFactoryfactory=newClassPathXmlApplicationContext(); UserServiceservice=newUserService(); ewInstance(); (id,o); oUpperCase()+(1); "methodName="+methodName); etMethod(methodName,().getInterfaces()[0]); DI與IOC相對(duì)來(lái)說(shuō)是一樣的概念。編輯xml文件時(shí),沒(méi)有提示window–preferences–myeclipse–FilesandEditing-xml–xmlcatalogadd按鈕Location: D:\share\0900_Spring\soft\ Type: SchemaLocationKey: 注入類型(Injectingdependencies)setter(重要)構(gòu)造方法(使用的非常少)接口注入(可以忘記)setter注入類型SetterInjection 就是在bean中使用setXXX方法進(jìn)行注入來(lái) 在bean類中,成員屬性需要setXXX方法如下:publicclassUserService{ privateUserDaouserDao=newUserDaoImpl(); publicUserDaogetUserDao(){ returnuserDao; } publicvoidsetUserDao(UserDaouserDao){ =userDao; } publicvoidadd(Useru){ (u);}}spring配置文件如下:<beanid="u"class=""></bean><beanid="userService"class=""> <propertyname="userDao"ref="u"/><!--這里的ref表示參考id=u的那個(gè)bean--> <!--或是下面的方式 <propertyname="userDao"> <refbean="u"></ref> </property>--></bean>構(gòu)造方法ConstructorInjection首先在bean類中需要有成員屬性作為參數(shù)的構(gòu)造方法 代碼如下:publicclassUserService{ privateUserDaouserDao=newUserDaoImpl(); publicUserService(UserDaouserDao){ super(); =userDao; } publicUserDaogetUserDao(){returnuserDao;} publicvoidsetUserDao(UserDaouserDao){ =userDao;} publicvoidadd(Useru){ (u);}}注意:背景較深的代碼為構(gòu)造方法,帶有參數(shù)的構(gòu)造方法spring配置文件如下:<beanid="u"class=""></bean><beanid="userService"class=""> <constructor-arg> <beanclass=""></bean> <!--<refbean="u"/>--> <!-- 需要注意的: 使用<bean>表示,重新new一個(gè)bean然后注入進(jìn)去, 使用<ref>表示,使用已經(jīng)new好的bean,這是只是引用它。 --> </constructor-arg></bean>使用<constructor-arg>和其子標(biāo)簽<bean>或<ref>進(jìn)行構(gòu)造方法注入當(dāng)構(gòu)造方法注入時(shí),構(gòu)造方法中有多個(gè)參數(shù)時(shí),可以使用以下兩種方式注入:bean代碼:publicclassExampleBean{privateintyears;privateStringultimateAnswer;publicExampleBean(intyears,StringultimateAnswer){=years;=ultimateAnswer;}}1、參數(shù)類型方式進(jìn)行區(qū)分參數(shù):xml配置文件:<beanid="exampleBean"class=""> <constructor-argtype="int"value="7500000"/><constructor-argtype=""value="42"/></bean>注意:這樣就是參數(shù)類型為int的注入7500000,而參數(shù)類型為的參數(shù)注入”42”,但這個(gè)方法不適合多個(gè)參數(shù)是相同的類型。2、利用索引進(jìn)行區(qū)分參數(shù)xml配置文件<beanid="exampleBean"class=""><constructor-argindex="0"value="7500000"/><constructor-argindex="1"value="42"/></bean>注意:index=0的注入到第一個(gè)參數(shù),index=1的注入到第二個(gè)參數(shù)。構(gòu)造方法的注入不方便,所以我們需要使用setter注入方式。id、name注xml配置文件中<bean>標(biāo)簽中的屬性名稱如下:<beanid="u"class=""></bean>或<beanname="u"class=""></bean>以上標(biāo)簽中的屬性id與name作用是一樣,唯一的區(qū)別:id中不可以含有特殊字符,而name中可以有特殊字符簡(jiǎn)單屬性的注入當(dāng)bean中存在簡(jiǎn)單屬性時(shí)的注入方式:bean代碼如下:publicclassUserDaoImplimplementsUserDao{ privateintdaoId; privateStringdaoStatus; publicintgetDaoId(){returndaoId;} publicvoidsetDaoId(intdaoId){=daoId; } publicStringgetDaoStatus(){ returndaoStatus; } publicvoidsetDaoStatus(StringdaoStatus){=daoStatus;} @Override publicvoidsave(Useru){"usersave...");}}xml配置文件如下:<beanid="u"class=""> <propertyname="daoId"value="8"></property> <propertyname="daoStatus"> <value>good</value> </property></bean>直接使用value屬性或是<value>子標(biāo)簽來(lái)注入Bean的作用范圍scope在Spring配置文件中的<bean>標(biāo)簽可以指定bean的作用范圍利用<bean>標(biāo)簽中的scope屬性來(lái)指定scope值:singleton單例:每次取出的bean都是同一個(gè)bean。默認(rèn)就是這個(gè)prototype原型:每次取的bean時(shí),都會(huì)重新創(chuàng)建一個(gè)新的beanrequestsessionglobalsession實(shí)例:<beanid="u"class=""></bean><beanname="userService"class=""scope="prototype"> <propertyname="userDao"ref="u"/> </bean>注意:只有spring與web框架結(jié)合時(shí)才會(huì)使用request/session/globalsession,但也非常少用,因?yàn)槠渌蚣芤呀?jīng)有功能非常強(qiáng)大的scope了(例如:struts的scope)集合注入很少用,不重要,參考程序<beanid="u"class=""> <propertyname="properties"> <props> <propkey="administrator"</prop> <propkey="support"</prop> <propkey="development"</prop> </props> </property> <propertyname="list"> <list> <value>alistelementfollowedbyareference</value> <refbean="myDataSource"/> </list> </property> <propertyname="map"> <map> <entry> <key> <value>anentry</value> </key> <value>justsomestring</value> </entry> <entry> <key> <value>aref</value> </key> <refbean="myDataSource"/> </entry> </map> </property> <propertyname="set"> <set> <value>justsomestring</value> <refbean="myDataSource"/> </set> </property> </bean>自動(dòng)裝配autowire含義:在bean注入時(shí)不需要我們來(lái)指定注入哪個(gè)具體的bean,而spring容器會(huì)根據(jù)我的使用autowire屬性來(lái)確定自動(dòng)裝配功能。autowire值:autodetect;byName:根據(jù)bean中成員屬性的名稱來(lái)自動(dòng)裝配byType:根據(jù)bean中成員屬性的類型來(lái)自動(dòng)裝配。constaractordefault:會(huì)根據(jù)<beans>標(biāo)簽中的default-autowire屬性來(lái)進(jìn)行自動(dòng)裝配的方式no(默認(rèn)就是這個(gè),需要手動(dòng)指定注入那個(gè)bean)byName根據(jù)bean中成員屬性的名稱來(lái)自動(dòng)裝配。bean代碼:UserDaoImpl類publicclassUserDaoImplimplementsUserDao{ privateintdaoId; publicintgetDaoId(){returndaoId;} publicvoidsetDaoId(intdaoId){=daoId; } @Override publicStringtoString(){ return"daoId="+; }}UserService類publicclassUserService{ privateUserDaouserDao=newUserDaoImpl(); publicUserDaogetUserDao(){ returnuserDao; } publicvoidsetUserDao(UserDaouserDao){ =userDao; } publicvoidadd(Useru){ (u); }}spring的配置文件<beanid="userDao"class=""> <propertyname="daoId"value="1"></property></bean><beanid="userDao2"class=""> <propertyname="daoId"value="2"></property></bean><beanname="userService"class=""scope="prototype"autowire="byName"></bean>測(cè)試代碼: publicvoidtestAdd_4()throwsException{ ApplicationContextfactory=newClassPathXmlApplicationContext(""); UserServiceservice=(UserService)("userService"); }結(jié)果:daoId=1說(shuō)明:因?yàn)樵谂渲梦募信渲昧藘蓚€(gè)UserDaoImpl(名稱分別:userDao、userDao2)和一個(gè)UserService類。而在userService的bean中并沒(méi)有進(jìn)行注入配置。而是使用了autowire屬性指定了byName值,這樣結(jié)果是正確的,是因?yàn)閟pring看到autowire=byName后,會(huì)在配置文件中查找bean的id與userService成員屬性名稱一至,然后將其注入,這樣就完成了根據(jù)名稱自動(dòng)裝配功能。byType根據(jù)類型自動(dòng)裝配:就是spring在初始化時(shí),會(huì)在配置文件中查找<bean>的類型與userService成員屬性的類型相比較,類型一致的將其注入,這樣就完成了根據(jù)類型自動(dòng)裝配。注意自動(dòng)裝配使用并不多;只有在使用anntation注解時(shí)會(huì)使用的。byType如果出現(xiàn)相同類型在兩個(gè)以上,就會(huì)出現(xiàn)異常。生命周期lazy-init/default-lazy-init(不重要)bean的何時(shí)初始化lazy-init值:default:表示使用<beans>標(biāo)簽中的default-lazy-init值 true:表示context在初始化時(shí),不會(huì)初始化這個(gè)bean,只有在使用時(shí)才會(huì)初始化 false:表示context在初始化時(shí),就會(huì)初始化這個(gè)bean例如:<xmlversion=""encoding="UTF-8"><beansxmlns=""xmlns:xsi=""xsi:schemaLocation=""default-lazy-init="false"><beanid="userDao"class=""lazy-init="true"> <propertyname="daoId"value="1"></property></bean><beanid="userDao2"class=""lazy-init="default"> <propertyname="daoId"value="2"></property></bean><beanname="userService"class=""lazy-init="false"></bean></beans>init-methoddestroy-method不要和prototype一起用(了解)init-method:用于<bean>標(biāo)簽中的屬性,表示在初始化這個(gè)bean之前所需要的執(zhí)行方法destroy-method:用于<bean>標(biāo)簽中的屬性,表示在這個(gè)bean銷毀時(shí)所需要的執(zhí)行方法。例如關(guān)閉連接池。注意:此屬性不要與scpoe=”prototype”一起使用,否則會(huì)出現(xiàn)其它的問(wèn)題。例如:<beanid="u"class=""> <propertyname="daoId"value="1"></property></bean><beanname="userService"class=""init-method="init"destroy-method="destroy"> <propertyname="userDao"ref="u"></property></bean>userService類的代碼publicclassUserService{ publicvoidinit(){ "現(xiàn)在開(kāi)始初始化UserService"); } privateUserDaouserDao=newUserDaoImpl(); publicUserDaogetUserDao(){returnuserDao; } publicvoidsetUserDao(UserDaouserDao){=userDao;} publicvoidadd(Useru){ (u);} publicvoiddestroy(){"destory"); }}測(cè)試代碼: publicvoidtestAdd_4()throwsException{ ClassPathXmlApplicationContextfactory=newClassPathXmlApplicationContext(""); UserServiceservice=(UserService)("userService"); .");} @Override publicvoiddelete(Useru){"userdelete...");}}UserService(業(yè)務(wù)層)publicclassUserService{ privateUserDaouserDao=newUserDaoImpl(); publicUserDaogetUserDao(){returnuserDao;} publicvoidsetUserDao(UserDaouserDao){=userDao;} publicvoidadd(Useru){ (u);} publicvoiddelete(Useru){ (u);}}User(實(shí)體對(duì)象)publicclassUser{ privateStringusername; privateStringpassword; publicStringgetUsername(){returnusername; } publicvoidsetUsername(Stringusername){=username;} publicStringgetPassword(){returnpassword; } publicvoidsetPassword(Stringpassword){=password;} }Spring的配置文件<beans> <beanid="u"class=""/> <beanid="userService"class=""> <!--<propertyname="userDao"bean="u"/>--> </bean></beans>需要處理的日志類(實(shí)現(xiàn)了InvocationHandler接口)只有實(shí)現(xiàn)了InvocationHandler接口的類才可以進(jìn)行動(dòng)態(tài)代理publicclassLogIntroductionimplementsInvocationHandler{privateObjecttergert; publicLogIntroduction(UserDaouserDao){=userDao;}etClassLoader(),newClass[]{},li); Useru=newUser(); (userDaoProxy); (u); (u);}結(jié)果:beforMethodusersave...beforMethoduserdelete...這樣就在執(zhí)行每個(gè)方法之前加入日志處理程序了。就是利用JAVA的動(dòng)態(tài)代理實(shí)現(xiàn)的。第八課:SpringAOP配置選項(xiàng) Spring實(shí)現(xiàn)動(dòng)態(tài)代理配置是有兩種配置文件:xml文件方式;annotation方式(使用AspectJ類庫(kù)實(shí)現(xiàn)的。)AOP配置annotation方式搭建annotation開(kāi)發(fā)環(huán)境首先:需要在配置文件中加入@AspectJ標(biāo)簽<aop:aspectj-autoproxy/>自動(dòng)幫我產(chǎn)生代理注意:Spring默認(rèn)并沒(méi)有加入aop的xsd文件,因?yàn)槲覀冃枰謩?dòng)加入(紅色部分)<beansxmlns=""xmlns:xsi=""xmlns:context=""xmlns:aop=""xsi:schemaLocation=""> <context:annotation-config/> <context:component-scanbase-package=""/> <aop:aspectj-autoproxy/></beans> 另外需要引用aspectJ的jar包: aspectJ類庫(kù)AspectJ是一個(gè)專門用來(lái)實(shí)現(xiàn)動(dòng)態(tài)代理(AOP編程)的類庫(kù)AspectJ是面向切面編程的框架Spring使用就是這個(gè)類庫(kù)實(shí)現(xiàn)動(dòng)態(tài)代理的AOP的annotation實(shí)例要求:在執(zhí)行save()方法之前加入日志邏輯spring的配置文件同上面的model類、dao層類、service層類都與上面天下一致切面類(LogInterceptor)importclassLogInterceptor{ @Before("execution(publicvoid") publicvoidbefore(){ "methodstart..."); } } 結(jié)果:這樣在運(yùn)行publicvoid方法之前就會(huì)先執(zhí)行這個(gè)邏輯了。 注意: 1、@Aspect:意思是這個(gè)類為切面類 2、@Componet:因?yàn)樽鳛榍忻骖愋枰猄pring管理起來(lái),所以在初始化時(shí)就需要將這個(gè)類初始化加入Spring的管理; 3、@Befoe:切入點(diǎn)的邏輯(Advice) 4、execution…:切入點(diǎn)語(yǔ)法三個(gè)連接點(diǎn)(切入點(diǎn))AspectJ的專業(yè)術(shù)語(yǔ)三個(gè)連接點(diǎn)(切入點(diǎn))JoinPoint切入面連接點(diǎn)(切入點(diǎn))切入面程序執(zhí)行過(guò)程程序執(zhí)行過(guò)程PointCut切入點(diǎn)人集合當(dāng)需要定義一個(gè)切入點(diǎn)時(shí),則需要使用這個(gè)@Pointcut("execution(*")publicvoidbusinessService(){}Aspect切面Advice切入點(diǎn)的邏輯例如上例中的@BeforeTarget被代理對(duì)象Weave織入織入點(diǎn)語(yǔ)法無(wú)返回值、方法參數(shù)為Userexecution(publicvoid任何包、任何類、任何返回值、任何方法的任何參數(shù)execution(public**(..))任何包、任何類、任何返回值、任何set開(kāi)頭方法的任何參數(shù)execution(*set*(..))任何返回值、類中的任何方法、任何參數(shù)execution(*任何返回值、包中任何類中的任何方法、任何參數(shù)execution(*任何返回值、包中任何層次子包(..)、任何類、任何方法、任何參數(shù)execution(*和!void(非void)execution(publicvoid!void注意:上以是AspectJ的織入點(diǎn)語(yǔ)法,SpringAOP也實(shí)現(xiàn)了自己的織入點(diǎn)語(yǔ)法,同樣可以使用within執(zhí)行方法之前@AspectpublicclassBeforeExample{@Before("")publicvoiddoAccessCheck(){.}}@AspectpublicclassBeforeExample{@Before("execution(*")publicvoiddoAccessCheck(){.}}@

AfterReturning方法正常執(zhí)行完之后@AspectpublicclassAfterReturningExample{@AfterReturning("")publicvoiddoAccessCheck(){.}}@AspectpublicclassAfterReturningExample{@AfterReturning(pointcut="",returning="retVal")publicvoiddoAccessCheck(ObjectretVal){.}}@

AfterThrowing方法拋出異常之后@AspectpublicclassAfterThrowingExample{@AfterThrowing("")publicvoiddoRecoveryActions(){.}}@AspectpublicclassAfterThrowingExample{@AfterThrowing(pointcut="",throwing="ex")publicvoiddoRecoveryActions(DataAccessExceptionex){.}}

@After(finally)方法拋出異常被catch之后,需要進(jìn)行的部分(相當(dāng)于finally功能)@AspectpublicclassAfterFinallyExample{@After("")publicvoiddoReleaseLock(){.}}@

Around在方法之前和之后都要加上但是需要一個(gè)參數(shù)ProceedingJoinPoint,并者需要ObjectretVal=();和返回returnretVal;@AspectpublicclassAroundExample{@Around("")publicObjectdoBasicProfiling(ProceedingJoinPointpjp)throwsThrowable{."); } @AfterReturning("myMethod()") publicvoidafterReturning(){ "methodafterreturning..."); }}注意:那個(gè)空方法,只是為了給Pointcut起個(gè)名字,以方便別處使用annotatin方式的AOP實(shí)例importclassLogInterceptor{ @Pointcut("execution(public*") publicvoidmyMethod(){}; @Before(value="myMethod()") publicvoidbefore(){ "methodstart..."); } @AfterReturning("myMethod()") publicvoidafterReturning(){ "methodafterreturning..."); } @Around(value="myMethod()") publicvoidaround(ProceedingJoinPointpjp)throwsThrowable{ ."); ."); }}AOP配置xml方式xml方式是我們以后使用的比較多的,因?yàn)楫?dāng)切面類我們沒(méi)有源代碼時(shí)、當(dāng)我們使用第三方的切面類時(shí),我就不能使用annotation的方式,而且如果使用annotation方式一但程序編譯后就不可以修改了。如果使用xml方式就不一樣了,我們只需要修改xml文件就可以了。xml方式與annotation的作用是一樣?,F(xiàn)在就是實(shí)例:<xmlversion=""encoding="UTF-8"><beansxmlns=""xmlns:xsi=""xmlns:context=""xmlns:aop=""xsi:schemaLocation=""> <context:annotation-config/> <context:component-scanbase-package=""/> <beanid="logInterceptor"class=""></bean> <aop:config> <!--<aop:pointcut>在此處定義的pointcut是全局的pointcut可以供所有的aspect使用 id:表示這個(gè)pointcut的名稱,以方便使用--> <aop:pointcutid="myMethod" expression="execution(public*"/> <!--<aop:aspect>表示定義一個(gè)切面類(這需要Spring初始化加入其管理) id:切面類的名稱, ref:引用哪個(gè)bean(需要使用<bean>標(biāo)簽初始化)--> <aop:aspectid="logAspect"ref="logInterceptor"> <!--在此處定義的pointcut是全局的pointcut只供當(dāng)前的aspect使用 id:表示這個(gè)pointcut的名稱,以方便使用 --> <aop:pointcutid="myMethod2" expression="execution(public*"/> <!-- 定義advice時(shí)的參數(shù) method:切面邏輯的方法名稱(切面類中的方法名) pointcut-ref:表示引用哪個(gè)pointcut(要求已經(jīng)在上面定義好了) pointcut:定義一個(gè)pointcut --> <aop:beforemethod="before"pointcut-ref="myMethod"/> <aop:after-returningmethod="afterReturning"pointcut="execution(public*"/> </aop:aspect> </aop:config></beans>AOP實(shí)現(xiàn)動(dòng)態(tài)代理注意因?yàn)镾pring要實(shí)現(xiàn)AOP(面向切面編程),需要加入切面邏輯的類就會(huì)生成動(dòng)態(tài)代理。在動(dòng)態(tài)代理類中加入切面類從而實(shí)現(xiàn)面向切面編程,但生成動(dòng)態(tài)代理存在以下注意事項(xiàng):被動(dòng)態(tài)代理的類如果實(shí)現(xiàn)了某一個(gè)接口,那么Spring就會(huì)利用JDK類庫(kù)生成動(dòng)態(tài)代理。如果被動(dòng)態(tài)代理的類沒(méi)有實(shí)現(xiàn)某一個(gè)接口,那么Spring就會(huì)利用CGLIB類庫(kù)直接修改二進(jìn)制碼來(lái)生成動(dòng)態(tài)代理(因?yàn)槔肑DK生成動(dòng)態(tài)代理的類必須實(shí)現(xiàn)一個(gè)接口),需要在項(xiàng)目中引用CGLIB類庫(kù)第九課:DataSource DataSource是一個(gè)接口 DataSource是一個(gè)標(biāo)準(zhǔn),其它只需要實(shí)現(xiàn)它的接口,然后隨意怎樣實(shí)現(xiàn)。 Sping配置數(shù)據(jù)源: <beanid="dataSource"class=""destroy-method="close"> <propertyname="driverClassName"value=""/> <propertyname="url"value="jdbc:"/> <propertyname="username"value="root"/> <propertyname="password"value="root"/> </bean>或者Planceholder(占位符的方式)配置數(shù)據(jù)源 <!-- 下面是使用占位符(Placeholder)的方式配置數(shù)據(jù)源 首先需要配置一個(gè)占位符類bean 然后給其注入properties配置文件 classpath:表示classpath下的文件 再是在配置數(shù)據(jù)源時(shí)可以使用占位符(${})獲取一些值 例如:${}:表示獲取配置文件中項(xiàng)的值等。 --> <bean class=""> <propertyname="locations"> <value>classpath:</value> </property> </bean> <beanid="dataSource"destroy-method="close" class=""> <propertyname="driverClassName"value="${}"/> <propertyname="url"value="${}"/> <propertyname="username"value="${}"/> <propertyname="password"value="${}"/> </bean>文件=注入使用然后在其它的bean中自動(dòng)注入(Spring需要使用的功能),就可以使用了。@Component("userDaoImpl")publicclassUserDaoImplimplementsUserDao{ privateDataSourcedataSource; publicDataSourcegetDataSource(){returndataSource;} @Resource(name="dataSource") publicvoidsetDataSource(DataSourcedataSource){ =dataSource;} @Override publicvoidsave(Useru){ try{ Connectionconn=(); ().executeUpdate("insertintouservalues(null,'wjt276')"); (); }catch(SQLExceptione){ ();}"usersave..."); }}#<!--初始化連接-->initialSize=10#<!--最大空閑連接-->maxIdle=20#<!--最小空閑連接-->minIdle=5#最大連接數(shù)量maxActive=50#是否在自動(dòng)回收超時(shí)連接的時(shí)候打印連接的超時(shí)錯(cuò)誤logAbandoned=true#是否自動(dòng)回收超時(shí)連接removeAbandoned=true#超時(shí)時(shí)間(以秒數(shù)為單位)removeAbandonedTimeout=180#<!--超時(shí)等待時(shí)間以毫秒為單位6000毫秒/1000等于60秒-->maxWait=1000第十課Spring整合Hiberante3Spring整合hibernate3重點(diǎn)就是需要初始化SessionFactory這個(gè)bean,需要在Spring的配置文件中進(jìn)行配置,實(shí)現(xiàn)實(shí)例如下:Spring配置hibernate3的SessionFactory實(shí)現(xiàn)上x(chóng)ml方式的配置文件與annotation注解方式的區(qū)別,只是在配置時(shí)所使用的bean不一樣,而且配置實(shí)體類所使用的屬性也不一樣(xml:mappingResources;annotation:annotatedClasses),如下:xml形式的SessionFactory <!--hibernater的xml方式LocalSessionFactoryBean是處理xml方式的bean 再利用mappingResources來(lái)配置實(shí)體類(model)映射文件 再利用hibernateProperties來(lái)配置相關(guān)屬性--><beanid="mySessionFactory"class=""><propertyname="dataSource"ref="dataSoure"/><propertyname="mappingResources"><list><value></list></property><propertyname="hibernateProperties"> <props> <propkey=""> <propkey="show_sql">true</prop> <propkey="format_sql">true</prop> </props></property>annotation注解方式的SessionFactory<!--hibernater的xml方式AnnotationSessionFactoryBean是處理annotation方式的bean 再利用annotatedClasses來(lái)配置實(shí)體類(model)是否進(jìn)行了注解 再利用hibernateProperties來(lái)配置相關(guān)屬性--><beanid="mySessionFactory"class=""><propertyname="dataSource"ref="dataSource"/><propertyname="annotatedClasses"><list><value></list></property><propertyname="hibernateProperties"> <props> <propkey=""> <propkey="">true</prop> <propkey="">true</prop> </props></property>注意:配置SessionFactory要求前面已經(jīng)配置了一個(gè)數(shù)據(jù)源的bean了,這里的dataSource引用了那個(gè)bean,同時(shí),在dao層中的dataSource成員屬性要求使用自動(dòng)裝配功能,進(jìn)行自動(dòng)注入。將指定包的實(shí)體類全部掃描到SessionFactory注意:如果您想在某一包或子包下掃描需要實(shí)現(xiàn)類,那么在annotation下配置SessionFactory可以使用annotatedPackages選項(xiàng)指定實(shí)體類所在包的包路徑就可以了。這樣就不需要把所有的實(shí)體類都配置這樣了。<propertyname="packagesToScan"> <list> <value> </list></property>這樣就不需要使用annotatedClassess來(lái)一個(gè)一個(gè)配置實(shí)現(xiàn)類了。只要將實(shí)現(xiàn)類所有的包配置進(jìn)來(lái)就可以了??梢耘渲枚鄠€(gè)包路徑。引入hibernate所需要使用的jar基本jarHibernatecore/lib/requiredSlf-nopjarmysql的JDBC驅(qū)動(dòng)名加入annotation功能的jar包HibernateannotationjarEjb3persistencejarHibernatecommonannotationsjar搭建日志環(huán)境并配置顯示DDL語(yǔ)句jar包我們使用slf接口,然后使用log4j的實(shí)現(xiàn)。首先引入log4j的jar包,然后再引入slf4j實(shí)現(xiàn)LOG4J和適配器jar包最后創(chuàng)建log4j的配置文件,并加以修改,只要保留 注意:在引入jar包時(shí),一定要小心,可少引入,再根據(jù)錯(cuò)誤提示引入其它包,但不可以多引入或引入不同版本或錯(cuò)誤的jar,否則會(huì)出現(xiàn)想不到的異常。Spring整合hibernate3事務(wù)Spring整合hiberante最常用的就是整合事務(wù)管理(TransactionManager)當(dāng)Spring整合hibernate事務(wù)后,默認(rèn)就是運(yùn)行期異常RunTimeException,Spring自動(dòng)回滾Annotation注解方式配置事務(wù)管理<xmlversion=""encoding="UTF-8"><beansxmlns="" xmlns:xsi="" xmlns:context="" xmlns:aop="" xmlns:tx="" xsi:schemaLocation=""> <context:annotation-config/> <context:component-scanbase-package=""/> <!--下面是使用占位符(Placeholder)的方式配置數(shù)據(jù)源 首先需要配置一個(gè)占位符類bean 然后給其注入properties配置文件 classpath:表示classpath下的文件 再是在配置數(shù)據(jù)源時(shí)可以使用占位符(${})獲取一些值 例如:${}:表示獲取配置文件中項(xiàng)的值等。 --> <bean class=""> <propertyname="locations"> <value>classpath:</value> </property> </bean> <beanid="dataSource"destroy-method="close" class=""> <propertyname="driverClassName"value="${}"/> <propertyname="url"value="${}"/> <propertyname="username"value="${}"/> <propertyname="password"value="${}"/> </bean><!--hibernater的xml方式AnnotationSessionFactoryBean是處理annotation方式的bean 再利用annotatedClasses來(lái)配置實(shí)體類(model)是否進(jìn)行了注解 再利用hibernateProperties來(lái)配置相關(guān)屬性 --><beanid="sessionFactory"class=""> <propertyname="dataSource"ref="dataSource"/> <propertyname="annotatedClasses"> <list> <value> <value> </list> </property> <propertyname="hibernateProperties"> <props> <propkey=""> <propkey="">true</prop> <propkey="">true</prop> </props> </property></bean><beanid="txManager"class=""> <propertyname="sessionFactory"ref="sessionFactory"/></bean><tx:annotation-driventransaction-manager="txManager"/> </beans>說(shuō)明:首先:如果想使用Spring管理事務(wù),則首需要在配置文件中加入下列(上面紅色加粗部分): xmlns:tx="" xsi:schemaLocation=”">其次:配置一個(gè)事務(wù)管理器的bean,這里使用的是Hibernate的事務(wù)管理HibernateTransactionManager,也可以使用,并且需要注入一個(gè)SessionFactory的bean,利用這個(gè)bean可以獲取數(shù)據(jù)源配置等其它的數(shù)據(jù)庫(kù)信息。但要求已經(jīng)在這之前配置了一個(gè)SessionFactory的bean了。<beanid="txManager"class=""> <propertyname="sessionFactory"ref="sessionFactory"/></bean>再次:需要在配置文件中告訴Spring,我們需要使用Spring來(lái)管理事務(wù),并且要告訴它,使用哪個(gè)事務(wù)管理器(這里我們就使用上面的剛則配置的txManager),<tx:annotation-driventransaction-manager="txManager"/> 注意:這里我們是使用annotation注解方式配置事務(wù)管理,所以使用<tx:annotation-driven>標(biāo)簽最后:就是對(duì)什么方法進(jìn)行事務(wù)管理,只需要在這個(gè)方法上加上@Transactional。如下:@Transactional publicvoidadd(Useru){……}這樣,Spring就會(huì)對(duì)這個(gè)方法進(jìn)行事務(wù)管理了。實(shí)例:場(chǎng)景:當(dāng)保存一個(gè)用戶后,需要向數(shù)據(jù)庫(kù)添加一條日志記錄,說(shuō)明已經(jīng)添加一個(gè)用戶了。需要使用Spring管理其事務(wù),如果兩者有一者發(fā)生異常,執(zhí)都需要進(jìn)行回滾。Spring的配置文件同上;代碼Log實(shí)體類@Entity@Table(name="t_log")publicclassLog{ privateintid; privateStringmsg; ……}User實(shí)體類@EntitypublicclassUser{ privateintid; privateStringname; ……}UserDao接口的實(shí)現(xiàn)@Component("userDaoImpl")publicclassUserDaoImplimplementsUserDao{ privateSessionFactorysessionFactory; publicSessionFactorygetSessionFactory(){returnsessionFactory;} ."); }}LogDao接口的實(shí)現(xiàn)@Component("logDaoImpl")publicclassLogDaoImplimplementsLogDao{ privateSessionFactorysessionFactory; publicSessionFactorygetSessionFactory(){returnsessionFactory;} ."); }}業(yè)務(wù)層代碼@Component(value="userService")publicclassUserService{ privateUserDaouserDao=newUserDaoImpl(); privateLogDaologDao; publicLogDaogetLogDao(){ returnlogDao;}只讀型事務(wù)超時(shí)timeoutint型(以秒為單位)事務(wù)超時(shí)回滾異常類(rollbackFor)一組Class類的實(shí)例,必須是Throwable的子類一組異常類,遇到時(shí)必須進(jìn)行回滾。默認(rèn)情況下checkedexceptions不進(jìn)行回滾,僅uncheckedexceptions(即RuntimeException的子類)才進(jìn)行事務(wù)回滾?;貪L異常類名(rollbackForClassname)一組Class類的名字,必須是Throwable的子類一組異常類名,遇到時(shí)必須進(jìn)行回滾不回滾異常類(noRollbackFor)一組Class類的實(shí)例,必須是Throwable的子類一組異常類,遇到時(shí)必須不回滾。不回滾異常類名(noRollbackForClassname)一組Class類的名字,必須是Throwable的子類一組異常類,遇到時(shí)必須不回滾Propagationkey屬性確定代理應(yīng)該給哪個(gè)方法增加事務(wù)行為。這樣的屬性最重要的部份是傳播行為。有以下選項(xiàng)可供使用:PROPAGATION_REQUIRED--支持當(dāng)前事務(wù),如果當(dāng)前沒(méi)有事務(wù),就新建一個(gè)事務(wù)。這是最常見(jiàn)的選擇。PROPAGATION_SUPPORTS--支持當(dāng)前事務(wù),如果當(dāng)前沒(méi)有事務(wù),就以非事務(wù)方式執(zhí)行。PROPAGATION_MANDATORY--支持當(dāng)前事務(wù),如果當(dāng)前沒(méi)有事務(wù),就拋出異常。PROPAGATION_REQUIRES_NEW--新建事務(wù),如果當(dāng)前存在事務(wù),把當(dāng)前事務(wù)掛起。PROPAGATION_NOT_SUPPORTED--以非事務(wù)方式執(zhí)行操作,如果當(dāng)前存在事務(wù),就把當(dāng)前事務(wù)掛起。PROPAGATION_NEVER--以非事務(wù)方式執(zhí)行,如果當(dāng)前存在事務(wù),則拋出異常。IsolationLevel(事務(wù)隔離等級(jí)):1、Serializable:最嚴(yán)格的級(jí)別,事務(wù)串行執(zhí)行,資源消耗最大;2、REPEATABLEREAD:保證了一個(gè)事務(wù)不會(huì)修改已經(jīng)由另一個(gè)事務(wù)讀取但未提交(回滾)的數(shù)據(jù)。避免了“臟讀取”和“不可重復(fù)讀取”的情況,但是帶來(lái)了更多的性能損失。3、READCOMMITTED:大多數(shù)主流數(shù)據(jù)庫(kù)的默認(rèn)事務(wù)等級(jí),保證了一個(gè)事務(wù)不會(huì)讀到另一個(gè)并行事務(wù)已修改但未提交的數(shù)據(jù),避免了“臟讀取”。該級(jí)別適用于大多數(shù)系統(tǒng)。4、ReadUncommitted:保證了讀取過(guò)程中不會(huì)讀取到非法數(shù)據(jù)。隔

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論