生活随笔
收集整理的這篇文章主要介紹了
SpringFramework-IOC(依赖注入)+AOP(面向切面编程)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄 簡介 IOC(控制反轉(zhuǎn)) HelloSpring IOC創(chuàng)建對象方式 Spring配置文件 依賴注入(DI) bean的作用域 bean 的自動裝配(autowire) 使用注解開發(fā) bean(@Component) 屬性注入(@Value("")) 衍生的注解 使用注解自動裝配(@Autowired) 作用域 使用Java的方式配置Spring 代理模式 AOP 使用Spring的API接口實現(xiàn) 自定義切入點類 注解實現(xiàn)AOP(@Aspect) 整合myBatis 事務(wù)
簡介
中文文檔
Spring Framework中文文檔
目的:解決企業(yè)應(yīng)用開發(fā)的復(fù)雜性
功能:使用基本的JavaBean代替EJB,并提供了更多的企業(yè)應(yīng)用功能
范圍:任何Java應(yīng)用
Spring是一個輕量級控制反轉(zhuǎn)(IoC)和面向切面(AOP)的容器框架。
Rod Johnson是spring Framework的創(chuàng)始人
Spring的理念:使現(xiàn)在的技術(shù)更加的容易使用,整合現(xiàn)有的技術(shù)框架
SSH:Struct2 + Spring + Hibernate
SSM:SpringMvc + Spring +MyBatis
優(yōu)點:
Spring是一個開源的免費的框架 Spring是一個輕量級的、非入侵式的框架 控制反轉(zhuǎn)(IOC ),面向切面編程(AOP ) 支持事務(wù)的處理 對框架的整合支持 Spring就是一個輕量級的控制反轉(zhuǎn)(IOC)和面向切面編程(AOP)的框架
Github地址 maven倉庫:
< dependency> < groupId> org.springframework
</ groupId> < artifactId> spring-webmvc
</ artifactId> < version> 5.2.8.RELEASE
</ version>
</ dependency>
< dependency> < groupId> org.springframework
</ groupId> < artifactId> spring-jdbc
</ artifactId> < version> 5.2.8.RELEASE
</ version>
</ dependency>
七大模塊
Spring Boot: 一個快速開發(fā)的腳手架 基于SpringBoot可以快速的開發(fā)單個微服務(wù) 約定大于配置 Spring Cloud:
IOC(控制反轉(zhuǎn))
之前,程序主動創(chuàng)建對象,控制權(quán)在底層 使用set注入,程序不再有主動權(quán),變成了被動的接收對象,降低系統(tǒng)耦合性 控制反轉(zhuǎn)是一種通過描述(XML或者注解)并通過第三方去生產(chǎn)或獲取特定對象的方式,在Spring中實現(xiàn)控制反轉(zhuǎn)的是IOC容器,其實現(xiàn)方法是依賴注入(Dependency Injection ,DI)
控制反轉(zhuǎn)IOC(Inversion of Control),是一種設(shè)計思想,沒有IoC的程序中,我們使用面向?qū)ο蟮木幊?#xff0c;對象的創(chuàng)建與對象間的依賴關(guān)系完全硬編碼在程序中,對象的創(chuàng)建由程序自己控制,控制反轉(zhuǎn)后將對象的創(chuàng)建轉(zhuǎn)移給第三方
HelloSpring
對象由Spring來創(chuàng)建,管理和裝配
創(chuàng)建一個測試類
public class Hello { private String str
; public String
getStr ( ) { return str
; } public void setStr ( String str
) { this . str
= str
; } @Override public String
toString ( ) { return "Hello{" + "str='" + str
+ '\'' + '}' ; }
}
在xml文件中注冊
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation= " http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd" > < bean id = " hello" class = " com.huang.pojo.Hello" > < property name = " str" value = " Spring" /> </ bean>
</ beans>
測試調(diào)用
public class myTest { @Test public void testHello ( ) { ApplicationContext context
= new ClassPathXmlApplicationContext ( "beans.xml" ) ; Hello hello
= ( Hello
) context
. getBean ( "hello" ) ; System
. out
. println ( hello
. toString ( ) ) ; }
}
IOC創(chuàng)建對象方式
在配置文件加載的時候,容器中管理的對象就已經(jīng)被創(chuàng)建了 無參構(gòu)造:property 有參構(gòu)造:constructor-arg
< bean id = " hello" class = " com.huang.pojo.Hello" >
< property name = " str" value = " Spring" />
< constructor-arg index = " 0" value = " huang" /> < constructor-arg type = " java.lang.String" value = " yaohui" /> <constructor-arg name="str" value="hanhan"
</ bean>
Spring配置文件
alias(別名)
< alias name = " hello" alias = " hello2" />
Bean的配置
id:bean的唯一標識符,也相當(dāng)于我們學(xué)的對象名 class:bean對象所對應(yīng)的全限定名 name:也是別名,可以起多個別名,可以用(,;空格)等來間隔
< bean id = " myname" class = " com.huang.pojo.Hello" name = " name1 name2,name3" > </ bean>
import
< import resource = " beans.xml" />
依賴注入(DI)
set注入
依賴注入:set注入 依賴:bean對象的創(chuàng)建依賴于容器 注入:bean對象中所有的屬性,由容器來注入 包含類型:
bean | ref | idref | list | set | map | props | value | null
< bean id = " student" class = " com.huang.pojo.Student" > < property name = " name" value = " persistenthuang" /> < property name = " hello" ref = " hello" /> < property name = " books" > < array> < value type = " java.lang.String" > 紅樓夢
</ value> < value type = " java.lang.String" > 西游記
</ value> < value type = " java.lang.String" > 水滸傳
</ value> < value type = " java.lang.String" > 三國演義
</ value> </ array> </ property> < property name = " hobby" > < list> < value type = " java.lang.String" > 聽歌
</ value> < value type = " java.lang.String" > 看電影
</ value> </ list> </ property> < property name = " card" > < map> < entry key = " cad1" value = " 123" /> < entry key = " cad2" value = " 123456" /> </ map> </ property> < property name = " games" > < set> < value type = " java.lang.String" > LoL
</ value> < value type = " java.lang.String" > 紅警
</ value> < value type = " java.lang.String" > 刀塔
</ value> </ set> </ property> < property name = " wife" > < null/> </ property> < property name = " properties" > < props> < prop key = " 學(xué)號" > 22111222
</ prop> < prop key = " 班級" > 三年二班
</ prop> < prop key = " 姓名" > persistenthuang
</ prop> </ props> </ property> </ bean>
c命名和p命名空間注入
P命名空間:可以直接注入屬性的值(property)
xmlns:p="http://www.springframework.org/schema/p"
//通過set注入
< bean id = " hello3" class = " com.huang.pojo.Hello" p: str= " huang" > </ bean>
C命名空間:
xmlns:c="http://www.springframework.org/schema/c"
//通過構(gòu)造器注入
< bean id = " hello4" class = " com.huang.pojo.Hello" c: str= " hhhh" > </ bean>
注意: p命名和c命名空間不能直接使用,要導(dǎo)入xml約束
bean的作用域
singleton(單例模式):Spring默認機制 prototype(原型模式):每次從容器中g(shù)et的時候都會產(chǎn)生一個新對象 其余request、session、application,在web開發(fā)中才能用
范圍使用描述 singleton(單例) scope=“singleton” (默認)為每個 Spring IoC 容器的單個 object 實例定義單個 bean 定義。 prototype(原型) scope=“prototype” 為任意數(shù)量的 object 實例定義單個 bean 定義。 request(請求) scope=“request” 將單個 bean 定義范圍限定為單個 HTTP 請求的生命周期。也就是說,每個 HTTP 請求都有自己的 bean 實例,該實例是在單個 bean 定義的后面創(chuàng)建的。僅在 web-aware Spring ApplicationContext的 context 中有效。 session scope=“session” 將單個 bean 定義范圍限定為 HTTP Session的生命周期。僅在 web-aware Spring ApplicationContext的 context 中有效。 application(應(yīng)用) 將單個 bean 定義范圍限定為ServletContext的生命周期。僅在 web-aware Spring ApplicationContext的 context 中有效。 WebSocket 將單個 bean 定義范圍限定為WebSocket的生命周期。僅在 web-aware Spring ApplicationContext的 context 中有效。
bean 的自動裝配(autowire)
使用注解開發(fā)
在使用Spring4之后,要使用注解開發(fā),必須保證aop包導(dǎo)入了 使用注解要導(dǎo)入context約束,增加注解支持注解支持
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xmlns: context= " http://www.springframework.org/schema/context" xsi: schemaLocation= " http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd" > < context: annotation-config/>
< context: component-scan base-package = " com.huang.pojo" />
</ beans>
bean(@Component)
加注解:@Component @Component:組件,放在類上,說明這個類被Spring管理了,就是bean
屬性注入(@Value(""))
加注解:@Value("") 可以放在屬性或者set方法上 適用簡單屬性,復(fù)雜屬性適用xml注入
衍生的注解
【@Component】有幾個衍生注解,在Web開發(fā)中,會按照mvc三層架構(gòu)分層 Dao:【@Repository】 Service:【@Service】 Controller:【@Controller】 這四個注解功能都一樣 ,代表將這個類注冊到Spring中,裝配Bean
使用注解自動裝配(@Autowired)
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xmlns: context= " http://www.springframework.org/schema/context" xsi: schemaLocation= " http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd" > < context: component-scan base-package = " com.huang.Dao" /> < context: annotation-config/>
</ beans>
使用Autowired我們可以不用編寫Set方法,前提是你這個自動裝配的屬性在IOC(Spring)容器中存在,且符合名字byName 顯示的定義了@Autowired(required = false),說明這個對象可以為空,否則不允許為空 @Nullable:字段標記了這個注解,說明這個注解可以為NULL @Qualifier(value=“指定的命名”):自動裝配環(huán)境比較復(fù)雜的時候,無法通過一個注解完成時添加的 不使用Autowired時可以使用@Resource(name="")
@Autowired ( required
= false ) @Qualifier ( value
= "hello2" ) private Hello hello
;
@Autowired和@Resource的區(qū)別 都是用來自動裝配的,都可以放在屬性字段上 @Autowired通過byType的方式實現(xiàn),而且必須要求這個對象存在 @Resource默認通過byName方式實現(xiàn),如果找不到名字,則通過byType實現(xiàn)
作用域
@Scope(“singleton”):單例模式
@Scope(“prototype”):原型模式
XML與注解
xml:更加萬能,適用于任何場合,維護簡單方便 注解:不是自己的類適用不了,維護相對復(fù)雜 xml與注解結(jié)合:
使用Java的方式配置Spring
不適用Spring的xml配置 JavaConfig是Spring的一個子項目,Spring4之后變成了核心功能
寫一個實體類
@Data
@Component
@Scope ( "singleton" )
public class User { @Value ( "huang" ) private String name
;
}
寫一個 配置類
@Configuration
@ComponentScan ( "com.huang" )
@Import ( config2
. class )
public class huangConfig { @Bean public User
getUser ( ) { return new User ( ) ; }
}
調(diào)用測試
@Test public void testHello ( ) { ApplicationContext context
= new AnnotationConfigApplicationContext ( huangConfig
. class ) ; User user
= context
. getBean ( "getUser" , User
. class ) ; System
. out
. println ( user
. toString ( ) ) ; }
代理模式
靜態(tài)代理
角色 抽象角色:一般會使用接口或者抽象類來解決 真實角色:被代理的角色 代理角色:代理真實角色,代理真實角色后,一般會做一些附屬操作 客戶角色:訪問代理對象的人 代理模式的好處: 可以使用真實角色的操作更加純粹,不用去關(guān)注一些公共業(yè)務(wù) 公共業(yè)務(wù)也就交給了代理角色!實現(xiàn)了業(yè)務(wù)的分工 公共業(yè)務(wù)發(fā)生擴展的時候,方便集中管理 缺點: 一個真實角色就會產(chǎn)生一個代理角色,代碼量會翻倍,開發(fā)效率會變低 動態(tài)代理好處: 一個動態(tài)代理代理的是一類接口,一般就是對應(yīng)的一類業(yè)務(wù) 一個動態(tài)代理可以代理多個類,只要實現(xiàn)了同一個接口即可
動態(tài)代理
InvocationHandler是由代理實例的調(diào)用處理程序?qū)崿F(xiàn)的接口。 每個代理實例都有一個關(guān)聯(lián)的調(diào)用處理程序。 在代理實例上調(diào)用方法時,方法調(diào)用將被編碼并調(diào)度到其調(diào)用處理程序的invoke方法。
public class ProxyInvocationHandler implements InvocationHandler { private Object target
; public void setTarget ( Object target
) { this . target
= target
; } public Object
getProxy ( ) { return Proxy
. newProxyInstance ( this . getClass ( ) . getClassLoader ( ) , target
. getClass ( ) . getInterfaces ( ) , this ) ; } public Object
invoke ( Object proxy
, Method method
, Object
[ ] args
) throws Throwable
{ Object result
= method
. invoke ( target
, args
) ; return result
; }
}
測試使用:Host是一個繼承Rent接口的實現(xiàn)類,Rent是一個
public class Client { public static void main ( String
[ ] args
) { Host host
= new Host ( ) ; ProxyInvocationHandler handler
= new ProxyInvocationHandler ( ) ; handler
. setTarget ( host
) ; Rent proxy
= ( Rent
) handler
. getProxy ( ) ; proxy
. rent ( ) ; }
}
AOP
AOP(Aspect Oriented Programming)意為:面向切面編程,通過預(yù)編譯方式和運行期間動態(tài)代理實現(xiàn)程序功能的統(tǒng)一維護的一種技術(shù)。AOP是OOP的延續(xù),是軟件開發(fā)中的一個熱點,也是Spring框架中的一個重要內(nèi)容,是函數(shù)式編程的一種衍生范型。利用AOP可以對業(yè)務(wù)邏輯的各個部分進行隔離,從而使得業(yè)務(wù)邏輯各部分之間的耦合度降低,提高程序的可重用性,同時提高了開發(fā)的效率。
< dependency> < groupId> org.aspectj
</ groupId> < artifactId> aspectjweaver
</ artifactId> < version> 1.9.4
</ version> </ dependency>
提供聲明式事務(wù):允許用戶自定義切面
橫切關(guān)注點:跨越應(yīng)用程序多個模塊的方法或功能。即是,與我們業(yè)務(wù)邏輯無關(guān),但是我們需要關(guān)注的部分,就是橫切關(guān)注點。如日志,安全,緩存,事務(wù)等等 切面(ASPECT):橫切關(guān)注點,被模塊化的特殊對象。即,它是一個類 通知(Advice):切面必須要完成的工作。即,它是類中的一個方法 目標(Target):被通知對象 代理(Proxy):向目標對象應(yīng)用通知后創(chuàng)建的對象 切入點(PointCut):切面通知執(zhí)行的“地點”的定義 連接點(JointPoint):與切入點匹配的執(zhí)行點
使用Spring的API接口實現(xiàn)
創(chuàng)建兩個日志類繼承接口:MethodBeforeAdvice,AfterReturningAdvice
public class logBefore implements MethodBeforeAdvice { public void before ( Method method
, Object
[ ] objects
, Object o
) throws Throwable
{ System
. out
. println ( o
. getClass ( ) . getName ( ) + "的" + method
. getName ( ) + "被執(zhí)行了" ) ; }
} public class logAfter implements AfterReturningAdvice { public void afterReturning ( Object o
, Method method
, Object
[ ] objects
, Object o1
) throws Throwable
{ System
. out
. println ( "執(zhí)行了" + method
. getName ( ) ) ; }
}
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xmlns: aop= " http://www.springframework.org/schema/aop" xsi: schemaLocation= " http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd" > < bean id = " host" class = " com.Proxy.Host" /> < bean id = " logbefore" class = " com.Proxy.Log.logBefore" /> < bean id = " logafter" class = " com.Proxy.Log.logAfter" /> < aop: config> < aop: pointcut id = " pointCut" expression = " execution(* com.Proxy.Host.*(..))" /> < aop: advisor advice-ref = " logbefore" pointcut-ref = " pointCut" /> < aop: advisor advice-ref = " logafter" pointcut-ref = " pointCut" /> </ aop: config>
</ beans>
@Test public void testAOP ( ) { ApplicationContext context
= new ClassPathXmlApplicationContext ( "applicationContext.xml" ) ; Rent host
= ( Rent
) context
. getBean ( "host" ) ; host
. rent ( ) ; }
自定義切入點類
execution用法參考連接
public class DiyPointCut { private void before ( ) { System
. out
. println ( "===============before=============" ) ; } private void after ( ) { System
. out
. println ( "===============after=============" ) ; }
}
< bean id = " diy" class = " com.Proxy.Diy.DiyPointCut" /> < aop: config> < aop: aspect ref = " diy" > < aop: pointcut id = " point" expression = " execution(* com.Proxy.Host.*(..))" /> < aop: before method = " before" pointcut-ref = " point" /> < aop: after method = " after" pointcut-ref = " point" /> </ aop: aspect> </ aop: config>
注解實現(xiàn)AOP(@Aspect)
@Aspect
public class DiyPointCut { @Before ( "execution(* com.Proxy.Host.*(..))" ) private void before ( ) { System
. out
. println ( "===============before=============" ) ; } @After ( "execution(* com.Proxy.Host.*(..))" ) private void after ( ) { System
. out
. println ( "===============after=============" ) ; } @Around ( "execution(* com.Proxy.Host.*(..))" ) public void around ( ProceedingJoinPoint jp
) throws Throwable
{ System
. out
. println ( "===============around-before=============" ) ; Object proceed
= jp
. proceed ( ) ; System
. out
. println ( "===============around-after=============" ) ; }
}
< bean id = " diy" class = " com.Proxy.Diy.DiyPointCut" /> < aop: aspectj-autoproxy/>
整合myBatis
官方文檔
導(dǎo)入相關(guān)jar包 junit myBatis mysql數(shù)據(jù)庫 Spring aop myBatis-spring
< dependencies> < dependency> < groupId> junit
</ groupId> < artifactId> junit
</ artifactId> < version> 4.13
</ version> < scope> test
</ scope> </ dependency> < dependency> < groupId> mysql
</ groupId> < artifactId> mysql-connector-java
</ artifactId> < version> 5.1.49
</ version> </ dependency> < dependency> < groupId> org.mybatis
</ groupId> < artifactId> mybatis
</ artifactId> < version> 3.5.5
</ version> </ dependency> < dependency> < groupId> org.springframework
</ groupId> < artifactId> spring-webmvc
</ artifactId> < version> 5.2.8.RELEASE
</ version> </ dependency> < dependency> < groupId> org.springframework
</ groupId> < artifactId> spring-jdbc
</ artifactId> < version> 5.2.8.RELEASE
</ version> </ dependency> < dependency> < groupId> org.aspectj
</ groupId> < artifactId> aspectjweaver
</ artifactId> < version> 1.9.4
</ version> </ dependency> < dependency> < groupId> org.mybatis
</ groupId> < artifactId> mybatis-spring
</ artifactId> < version> 2.0.5
</ version> </ dependency> </ dependencies>
編寫數(shù)據(jù)源 sqlSessionFactory sqlSessionTemplate 給接口加實現(xiàn)類 將自己寫的實現(xiàn)類注入到mybatis 測試
方法一
@Data
public class User { int id
; String class_name
;
}
public interface UserMapper { public List
< User> selectUser ( ) ;
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
< mapper namespace = " com.huang.mapper.UserMapper" > < select id = " selectUser" resultType = " com.huang.pojo.User" > select * from school.test2
</ select>
</ mapper>
@Data
public class UserMapperImpl implements UserMapper { SqlSessionTemplate sqlSession
; public List
< User> selectUser ( ) { UserMapper mapper
= sqlSession
. getMapper ( UserMapper
. class ) ; return mapper
. selectUser ( ) ; }
}
myBatis-config.xml:mybatis的核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
< configuration>
</ configuration>
spring-dao.xml:整合配置文件,專注于mybatis的一些對象生成
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xmlns: aop= " http://www.springframework.org/schema/aop" xsi: schemaLocation= " http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd" > < bean id = " dataSource" class = " org.springframework.jdbc.datasource.DriverManagerDataSource" > < property name = " driverClassName" value = " com.mysql.jdbc.Driver" /> < property name = " url" value = " jdbc:mysql://localhost:3306/school?useSSL=false& useUnicode=true& characterEncoding=UTF-8" /> < property name = " username" value = " root" /> < property name = " password" value = " 123456" /> </ bean> < bean id = " sqlSessionFactory" class = " org.mybatis.spring.SqlSessionFactoryBean" > < property name = " dataSource" ref = " dataSource" /> < property name = " configLocation" value = " classpath:myBatis-config.xml" /> < property name = " mapperLocations" value = " classpath:com/huang/mapper/UserMapper.xml" /> </ bean> < bean id = " sqlSession" class = " org.mybatis.spring.SqlSessionTemplate" > < constructor-arg index = " 0" ref = " sqlSessionFactory" /> </ bean> </ beans>
applicationContext.xml:總配置文件,引入spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance" xmlns: aop= " http://www.springframework.org/schema/aop" xsi: schemaLocation= " http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd" > < import resource = " spring-dao.xml" /> < bean id = " userMapper" class = " com.huang.mapper.UserMapperImpl" > < property name = " sqlSession" ref = " sqlSession" /> </ bean> < bean id = " userMapper2" class = " com.huang.mapper.UserMapperImpl2" > < property name = " sqlSessionFactory" ref = " sqlSessionFactory" /> </ bean>
</ beans>
@Test public void testSB ( ) { ApplicationContext context
= new ClassPathXmlApplicationContext ( "applicationContext.xml" ) ; UserMapper userMapper
= context
. getBean ( "userMapper" , UserMapper
. class ) ; for ( User user
: userMapper
. selectUser ( ) ) { System
. out
. println ( user
. toString ( ) ) ; } }
方法二
不用創(chuàng)建sqlsession對象了,實現(xiàn)接口繼承一個SqlSessionDaoSupport對象
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper { public List
< User> selectUser ( ) { return getSqlSession ( ) . getMapper ( UserMapper
. class ) . selectUser ( ) ; }
}
< bean id = " userMapper2" class = " com.huang.mapper.UserMapperImpl2" > < property name = " sqlSessionFactory" ref = " sqlSessionFactory" /> </ bean>
事務(wù)
事務(wù)的ACID原則:原子性,一致性,隔離性,持久性
聲明式事務(wù)
使用AOP的方式
修改后的spring-dao.xml
< ? xml version
= "1.0" encoding
= "UTF-8" ? >
< beans xmlns
= "http://www.springframework.org/schema/beans" xmlns
: xsi
= "http://www.w3.org/2001/XMLSchema-instance" xmlns
: aop
= "http://www.springframework.org/schema/aop" xmlns
: tx
= "http://www.springframework.org/schema/tx" xsi
: schemaLocation
= "http
: / / www
. springframework
. org
/ schema
/ beanshttp
: / / www
. springframework
. org
/ schema
/ beans
/ spring
- beans
. xsdhttp
: / / www
. springframework
. org
/ schema
/ aophttp
: / / www
. springframework
. org
/ schema
/ aop
/ spring
- aop
. xsdhttp
: / / www
. springframework
. org
/ schema
/ txhttp
: / / www
. springframework
. org
/ schema
/ tx
/ spring
- tx
. xsd"
> < ! -- DataSource:使用spring的數(shù)據(jù)源替換mybatis的配置,使用spring提供的jdbc
-- > < bean id
= "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource" > < property name
= "driverClassName" value
= "com.mysql.jdbc.Driver" / > < property name
= "url" value
= "jdbc:mysql://localhost:3306/school?useSSL=false&useUnicode=true&characterEncoding=UTF-8" / > < property name
= "username" value
= "root" / > < property name
= "password" value
= "123456" / > < / bean
> < ! -- sqlSessionFactory
-- > < bean id
= "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" > < property name
= "dataSource" ref
= "dataSource" / > < ! -- 綁定myBatis
-- > < property name
= "configLocation" value
= "classpath:myBatis-config.xml" / > < property name
= "mapperLocations" value
= "classpath:com/huang/mapper/UserMapper.xml" / > < / bean
> < ! -- SqlSessionTemplate就是我們用的sqlSession
-- > < bean id
= "sqlSession" class = "org.mybatis.spring.SqlSessionTemplate" > < ! -- 只能使用構(gòu)造器注入,因為沒有set函數(shù)
-- > < constructor
- arg index
= "0" ref
= "sqlSessionFactory" / > < / bean
> < ! -- 配置聲明式事務(wù)
-- > < bean id
= "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" > < property name
= "dataSource" ref
= "dataSource" / > < / bean
>
< ! -- 結(jié)合AOP實現(xiàn)事務(wù)的織入
-- > < ! -- 配置事務(wù)的通知
-- > < tx
: advice id
= "txAdvice" transaction
- manager
= "transactionManager" > < ! -- 給哪些方法配置事務(wù)
-- > < ! -- 配置事務(wù)傳播特性
-- > < tx
: attributes
> < tx
: method name
= "*" propagation
= "REQUIRED" / > < / tx
: attributes
> < / tx
: advice
> < ! -- 配置事務(wù)切入
-- > < aop
: config
> < aop
: pointcut id
= "txPointCut" expression
= "execution(* com.huang.mapper.*.*(..))" / > < aop
: advisor advice
- ref
= "txAdvice" pointcut
- ref
= "txPointCut" / > < / aop
: config
> < / beans
>
總結(jié)
以上是生活随笔 為你收集整理的SpringFramework-IOC(依赖注入)+AOP(面向切面编程) 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔 推薦給好友。