1.Spring
1.簡介
Spring : 春天 --->給軟體行業帶來了春天
2002年,Rod Jahnson首次推出了Spring框架雛形interface21框架,
2004年3月24日,Spring框架以interface21框架為基礎,經過重新設計,發布了1.0正式版,
很難想象Rod Johnson的學歷 , 他是悉尼大學的博士,然而他的專業不是計算機,而是音樂學,
Spring理念 : 使現有技術更加實用 . 本身就是一個大雜燴 , 整合現有的框架技術
官網 : http://spring.io/
官方下載地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/
GitHub : https://github.com/spring-projects
2.優點
1、Spring是一個開源免費的框架 , 容器 .
2、Spring是一個輕量級的框架 , 非侵入式的 .
3、控制反轉 IoC , 面向切面 Aop
4、對事物的支持 , 對框架的支持
.......
一句話概括:
Spring是一個輕量級的控制反轉(IoC)和面向切面(AOP)的容器(框架),
3.組成

Spring 框架是一個分層架構,由 7 個定義良好的模塊組成,Spring 模塊構建在核心容器之上,核心容器定義了創建、配置和管理 bean 的方式 .

組成 Spring 框架的每個模塊(或組件)都可以單獨存在,或者與其他一個或多個模塊聯合實作,每個模塊的功能如下:
- 核心容器:核心容器提供 Spring 框架的基本功能,核心容器的主要組件是 BeanFactory,它是工廠模式的實作,BeanFactory 使用控制反轉(IOC) 模式將應用程式的配置和依賴性規范與實際的應用程式代碼分開,
- Spring 背景關系:Spring 背景關系是一個組態檔,向 Spring 框架提供背景關系資訊,Spring 背景關系包括企業服務,例如 JNDI、EJB、電子郵件、國際化、校驗和調度功能,
- Spring AOP:通過配置管理特性,Spring AOP 模塊直接將面向切面的編程功能 , 集成到了 Spring 框架中,所以,可以很容易地使 Spring 框架管理任何支持 AOP的物件,Spring AOP 模塊為基于 Spring 的應用程式中的物件提供了事務管理服務,通過使用 Spring AOP,不用依賴組件,就可以將宣告性事務管理集成到應用程式中,
- Spring DAO:JDBC DAO 抽象層提供了有意義的例外層次結構,可用該結構來管理例外處理和不同資料庫供應商拋出的錯誤訊息,例外層次結構簡化了錯誤處理,并且極大地降低了需要撰寫的例外代碼數量(例如打開和關閉連接),Spring DAO 的面向 JDBC 的例外遵從通用的 DAO 例外層次結構,
- Spring ORM:Spring 框架插入了若干個 ORM 框架,從而提供了 ORM 的物件關系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map,所有這些都遵從 Spring 的通用事務和 DAO 例外層次結構,
- Spring Web 模塊:Web 背景關系模塊建立在應用程式背景關系模塊之上,為基于 Web 的應用程式提供了背景關系,所以,Spring 框架支持與 Jakarta Struts 的集成,Web 模塊還簡化了處理多部分請求以及將請求引數系結到域物件的作業,
- Spring MVC 框架:MVC 框架是一個全功能的構建 Web 應用程式的 MVC 實作,通過策略介面,MVC 框架變成為高度可配置的,MVC 容納了大量視圖技術,其中包括 JSP、Velocity、Tiles、iText 和 POI,
4.拓展
Spring Boot與Spring Cloud
- Spring Boot 是 Spring 的一套快速配置腳手架,可以基于Spring Boot 快速開發單個微服務;
- Spring Cloud是基于Spring Boot實作的;
- Spring Boot專注于快速、方便集成的單個微服務個體,Spring Cloud關注全域的服務治理框架;
- Spring Boot使用了約束優于配置的理念,很多集成方案已經幫你選擇好了,能不配置就不配置 , Spring Cloud很大的一部分是基于Spring Boot來實作,Spring Boot可以離開Spring Cloud獨立使用開發專案,但是Spring Cloud離不開Spring Boot,屬于依賴的關系,
- SpringBoot在SpringClound中起到了承上啟下的作用,如果你要學習SpringCloud必須要學習SpringBoot,
2.Spring—IOC
1.在Maven專案中添加Spring依賴
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
</dependencies>
2.IOC的本質
控制反轉IoC(Inversion of Control),是一種設計思想,DI(依賴注入)是實作IOC的一種方法,在沒有IoC的程式中,我們使用面向物件的編程,物件的創建與物件間的依賴關系完全硬編碼在程式中,物件的創建由程式自己控制,控制反轉將物件的創建轉移給第三方,個人認為所謂控制反轉就是:獲得依賴物件的方式反轉了,
采用XML方式配置Bean的時候,Bean的定義資訊是和實作分離的,而采用注解的方式可以把兩者合為一體,Bean的定義資訊直接以注解的形式定義在實作類中,從而達到了零配置的目的,
控制反轉是通過描述(XML或注解)并通過第三方去生產或獲取特定物件的方式,在Spring中實作控制反轉的是IoC容器,其實作方法是依賴注入(Dependency Injection,DI),
3.配置Spring的元資料
<?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/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" >
<property name="name" value="https://www.cnblogs.com/aadzj/p/dengzhijiang"></property>
</bean>
<!-- more bean definitions go here -->
</beans>
4.獲取Spring的背景關系物件
讀取容器
ApplicationContext context = new ClassPathXmlApplicationContext("benas.xml");
5.Spring創建物件
<bean id="userService" >
<!--
ref:參考Spring容器中已經創建好的物件
value:基本的值,基本資料型別
-->
<property name="userDao" ref="oracle"></property>
</bean>
6.不同資料型別的注入方式
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private String wife;
<bean id="address" >
<property name="address" value="https://www.cnblogs.com/aadzj/p/湛江市"></property>
</bean>
<bean id="student" >
<!--第一種,普通值注入,value-->
<property name="name" value="https://www.cnblogs.com/aadzj/p/鄧志江" />
<!--第二種,bean注入,ref-->
<property name="address" ref="address"/>
<!--陣列-->
<property name="books">
<array>
<value>紅樓夢</value>
<value>西游記</value>
<value>水滸傳</value>
<value>三國演義</value>
</array>
</property>
<!--List-->
<property name="hobbies">
<list>
<value>聽歌</value>
<value>寫字</value>
<value>運動</value>
</list>
</property>
<!--map-->
<property name="card">
<map>
<entry key="省份證" value="https://www.cnblogs.com/aadzj/p/44088219981211"></entry>
<entry key="銀行卡" value="https://www.cnblogs.com/aadzj/p/201824113212"></entry>
</map>
</property>
<!--set-->
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property>
<!--null-->
<property name="wife">
<null/>
</property>
<!--properties-->
<property name="info">
<props>
<prop key="driver">20182411</prop>
<prop key="gender">男</prop>
<prop key="username">小明</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
7.擴展方式注入
c命名空間和p命名空間的注入:不能直接使用,需要匯入xml約束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
<!--p命名空間注入,可以直接注入屬性的值,property-->
<bean id="user" p:name="鄧志江" p:age="22"></bean>
<!--c命名空間注入,通過構造器注入,construct-args-->
<bean id="user2" c:name="林勇" c:age="22" ></bean>
8.bean的作用域
1、單例模式(Spring默認模式)
<bean id="user" p:name="鄧志江" p:age="22" scope="singleton"></bean>
2、原型模式(每次從容器中get的時候,都會產生一個新的物件!
<bean id="user2" c:name="林勇" c:age="22" scope="prototype"></bean>
3、其余的 @request、@sesstion、@application 這些只能在web開發中使用到!
9.bean的自動裝配
- autowired:byName ---> 必須保證所有的 bean 的 id 的唯一,并且這個 bean 需要和自動注入的屬性的 set 方法的值一致,
- autowired:byType ---> 必須保證所有的 bean 的 class 的唯一,并且這個 bean 需要和自動注入的屬性的型別一致!
private String name;
@Autowired
private Cat cat;
@Autowired
private Dog dog;
<!--自動裝配需要加上-->
<context:annotation-config/>
<bean id="cat" ></bean>
<bean id="dog" ></bean>
<!--
byName: 會自動在容器的背景關系中查找,和自己物件set方法后面值對應的 beanid!
byType: 會自動在容器的背景關系中查找,和自己物件屬性型別相同的 bean!
-->
<bean id="person" autowire="byName">
<property name="name" value="https://www.cnblogs.com/aadzj/p/小公羊"/>
<!--<property name="cat" ref="cat"/>-->
<!--<property name="dog" ref="dog"/>-->
</bean>
注解說明
-@autowired:自動裝配通過型別、名字
? 如果@autowired沒有自動裝配上屬性,則需要通過@qualifier(value = https://www.cnblogs.com/aadzj/p/“ ”)
-@nullable 如果欄位標記了這個注解,說明這個欄位可以為null
-@resource:自動裝配通過型別、名字
將類注冊到容器中
-@component :組件,放在這個類上,說明這個類被Spring管理了,就是bean!
? 等價于:
-@Value: 給屬性賦值,等價于:
<!--需要在 xml 中開啟注解掃描,才能檢測到注冊bean的類-->
<context:component-scan base-package="com.dzj.dao"/>
@component組件的衍生:在web開發中,會按照三層架構分層
dao【@Repository】
service【@Service】
controller【@Controller】
這四個注解功能都是一樣的,都是將我們的類注冊到Spring容器
10.在純java類中配置的方法
第一種方法:
1、在物體類的頭部添加注解--@component
@Value注解用來給物件的屬性賦值
@Component
public class User {
@Value("zhijiang")
public String name;
public void show(){
System.out.println("成功了...");
}
}
2、在配置類 MyConfig 中添加兩個注解
--@configuration ---> 代替 beans.xml 檔案,相當于這個類就是一個spring容器
--@componentScan --> 用來掃描物體類,哪些類注冊了 bean
@Configuration
@ComponentScan("com.dzj.pojo")
public class MyConfig {
}
3、獲取容器中的物件
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("user", User.class);
第二種方法:
1、無需在物體類中添加多余的注解,若想給物件的屬性賦值,只需用@Value注解給屬性賦值即可
public class User {
@Value("zhijiang")
public String name;
public void show(){
System.out.println("成功了...");
}
}
2、只需在配置類中添加一個回傳物件的方法,并且在該方法上方添加一個注解@bean
public class MyConfig {
@Bean
public User getUser(){
return new User();
}
}
@bean就是beans.xml檔案中的
方法名:getUser就是
new user():就是就是
3、獲取容器中的物件
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("getUser", User.class);
3.Spring—AOP
1.聊聊AOP

2.動態代理
2.1.被代理的介面
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
2.2.介面的實作類(真實角色)
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("添加了一個用戶");
}
public void delete() {
System.out.println("洗掉了一個用戶");
}
public void update() {
System.out.println("修改了一個用戶");
}
public void query() {
System.out.println("查詢了一個用戶");
}
}
2.3.自動生成代理類的中間類
//等會我們用這個類,自動生成代理類
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 {
PrintLog(method.getName());
Object result = method.invoke(target,args);
fee();
return result;
}
public void PrintLog(String msg){
System.out.println("[debug]執行了"+msg+"方法!");
}
public void fee(){
System.out.println("收中介費");
}
}
2.4.執行類
public static void main(String[] args) {
//真實角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色,不存在,從ProxyInvocationHandler類中動態生成
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//在 ProxyInvocationHandler 類中通過setTarget()方法得到要被代理的真是角色 userService
pih.setTarget(userService);
// 獲取代理角色
UserService proxy = (UserService) pih.getProxy();
proxy.add(); //執行代理實體,以及一些附屬的操作
}
3.在Spring中實作AOP
1.使用原生態 API介面
使用原生態 API介面**(主要是SpringAPI介面實作)
1. 創建介面,包含真實角色要實作的抽象方法
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
2. 實作介面的類(真實角色)
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("添加了一個用戶!");
}
public void delete() {
System.out.println("洗掉了一個用戶!");
}
public void update() {
System.out.println("修改了一個用戶!");
}
public void query() {
System.out.println("查詢了一個用戶!");
}
}
3. 執行環繞增強的類
public class Log implements MethodBeforeAdvice {
//method:要執行的目標物件的方法
//args:引數
//target:目標物件
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被執行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue:回傳值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("執行了"+method.getName()+"方法,回傳結果為:"+returnValue);
}
}
4. 創建并配置applicationContext.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/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注冊bean-->
<bean id="userService" />
<bean id="log" />
<bean id="afterLog" />
<!--方式一:使用原生態 API介面-->
<!--配置aop:需要匯入aop的約束-->
<aop:config>
<!--創建切入點:expression:運算式,excution(要執行的位置!* * * * *)-->
<aop:pointcut id="pointcut" expression="execution(* com.dzj.service.UserServiceImpl.*(..))" /> <!--執行環繞增強,把增強引入切入點-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
5. 添加測驗類
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//動態代理的是介面,而不是介面的實作類
UserService userService = context.getBean("userService", UserService.class);
userService.query();
}
}
2.自定義類(主要是切面定義)
1. 創建被代理的介面
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
2. 實作被代理介面的類(真實角色)
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("添加了一個用戶!");
}
public void delete() {
System.out.println("洗掉了一個用戶!");
}
public void update() {
System.out.println("修改了一個用戶!");
}
public void query() {
System.out.println("查詢了一個用戶!");
}
}
3. 自定義類
public class diy {
public void before(){
System.out.println("*****方法執行前*****");
}
public void after(){
System.out.println("*****方法執行后*****");
}
}
4. applicationContext.xml 組態檔
<!--注冊bean-->
<bean id="userService" />
<bean id="log" />
<bean id="afterLog" />
<!--方式二:自定義類-->
<bean id="diy" />
<aop:config>
<!--自定義切面,ref 要參考的類-->
<aop:aspect ref="diy">
<!--切入點-->
<aop:pointcut id="point" expression="execution(* com.dzj.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
5. 測驗類
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//動態代理的是介面,而不是介面的實作類
UserService userService = context.getBean("userService", UserService.class);
userService.query();
}
}
3.使用注解
1. 創建一個類,通過 @Aspect 注解的方式標注為此類為一個切面
@Aspect //標注這個類是一個切面
public class AnnotationPointCut {
@Before("execution(* com.dzj.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("*****方法執行前*****");
}
@After("execution(* com.dzj.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("*****方法執行后*****");
}
//在環繞增強中,我們可以給定一個引數,代表我們要獲取處理切入的點
@Around("execution(* com.dzj.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("環繞前");
Signature signature = jp.getSignature();//獲得簽名
System.out.println("signature:"+signature);
Object proceed = jp.proceed();//執行方法
System.out.println("環繞后");
}
}
2. applicationContext.xml組態檔
<!--方式三-->
<!--創建切入點-->
<bean id="annotationPointCut" />
<!--開啟注解支持--><aop:aspectj-autoproxy/>
3. 被代理的介面、實作類、測驗類均不變
4、AOP在Spring中的作用
提供宣告式事務,允許用戶自定義切面
(1)橫切切入點:跨越應用程式多個模塊的功能和方法,即是,與我們邏輯無關的,但是我們需要關注的部分,就是橫切關注點,如日志、安全、快取、事務等等......
(2)切面(ASPECT):橫切關注點 被模塊化的特殊物件,即,它是一個類,
(3)通知(Advice):切面必須要完成的作業,即,它是類中的一個方法,
(4)目標(Tatget):被通知的物件,
(5)代理(Proxy):向目標物件應用通知之后創建的物件,
(6)切入點(PointCut):切面通知 執行的 “地點” 的定義,
(7)連接點(JoinPoint):與切入點匹配的執行點,

4.Spring-Mybatis
1. 回憶Mybatis
1. 新建一個物體類
@Data
public class User {
private int uid;
private String username;
private String password;
}
2. 撰寫Mybatis核心組態檔
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.dzj.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="https://www.cnblogs.com/aadzj/p/com.mysql.jdbc.Driver"/>
<property name="url" value="https://www.cnblogs.com/aadzj/p/jdbc:mysql://localhost:3306/test"/>
<property name="username" value="https://www.cnblogs.com/aadzj/p/root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<!-- 將mapper檔案加入到組態檔中,注冊介面 -->
<mappers>
<mapper ></mapper>
</mappers>
</configuration>
3. 撰寫介面
public interface UserMapper {
public List<User> selectUser();
}
4. 撰寫介面對應的xml檔案
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dzj.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from test.user;
</select>
</mapper>
5. 撰寫測驗類
public class MyTest {
@Test
public void test() throws IOException {
String resources = "mybatis-config.xml";
InputStream in = Resources.getResourceAsStream(resources);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userlist = mapper.selectUser();
for(User user:userlist){
System.out.println(user);
}
}
}
2. Mybatis-Spring
1. 撰寫資料源配置
<!--DataSource使用Spring的資料源替換Mybatis的配置 c3p0、dbcp、druid也可以
我們這里使用Spring提供的JDBC : org.springframework.jdbc.datasource
-->
<bean id="dataSource" >
<property name="driverClassName" value="https://www.cnblogs.com/aadzj/p/com.mysql.jdbc.Driver"/>
<property name="url" value="https://www.cnblogs.com/aadzj/p/jdbc:mysql://localhost:3306/test"/>
<property name="username" value="https://www.cnblogs.com/aadzj/p/root"/>
<property name="password" value=""/>
</bean>
2. sqlSessionFactory
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" >
<property name="dataSource" ref="dataSource"/>
<!--系結Mybati組態檔-->
<property name="configLocation" value="https://www.cnblogs.com/aadzj/p/classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="https://www.cnblogs.com/aadzj/p/classpath:com/dzj/mapper/*.xml"/>
</bean>
3. sqlSessionTemplate
<!--SqlSessionTemplate:就是我們使用的sqlSession-->
<bean id="sqlSession" >
<!--只能使用構造器注入SQLSessionFactory,因為它沒有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
4. 需要給介面加實作類
public class UserMapperImpl implements UserMapper {
//我們所有的操作,都是用sqlSession來執行,在原來,現在都使用SqlSessionTemplate
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
5. 將自己寫的實作類,注入到Spring中
<import resource="spring-dao.xml"/>
<bean id="userMapper" >
<property name="sqlSession" ref="sqlSession"/>
</bean>
6. 測驗
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for(User user:userMapper.selectUser()){
System.out.println(user);
}
5.宣告式事務
1. 事務的特點
- 把一組業務當成一個業務來做,要么都成功要么都失敗,
- 事務在專案開發中,十分的重要,涉及到資料的一致性問題,不能馬虎,
- 確保一致性和完整性
事務ACID原則:
- 原子性
- 一致性
- 隔離性
- 多個業務可能同時操作同一個資源,防止資料損壞,
- 持久性
- 事務一旦被提交,無論系統發生什么問題,結果都不會被影響,被持久化的寫到存盤器中,
2. 事務的配置
<!--配置宣告式事務-->
<bean id="transactionManager" >
<property name="dataSource" ref="dataSource"/>
</bean>
<!--結合AOP實作事務的織入-->
<!--配置事務通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--給哪些事務配置方法-->
<!--配置事務的傳播特性:new propagation-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
<!--"name*" 代表所有方法-->
</tx:attributes>
</tx:advice>
<!--配置事務的切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.dzj.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
3. spring中的事務管理
Spring在不同的事務管理API之上定義了一個抽象層,使得開發人員不必了解底層的事務管理API就可以使用Spring的事務管理機制,Spring支持編程式事務管理和宣告式的事務管理,
編程式事務管理
- 將事務管理代碼嵌到業務方法中來控制事務的提交和回滾
- 缺點:必須在每個事務操作業務邏輯中包含額外的事務管理代碼
宣告式事務管理
- 一般情況下比編程式事務好用,
- 將事務管理代碼從業務方法中分離出來,以宣告的方式來實作事務管理,
- 將事務管理作為橫切關注點,通過aop方法模塊化,Spring中通過Spring AOP框架支持宣告式事務管理,
使用Spring管理事務,注意頭檔案的約束匯入 : tx
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
事務管理器
- 無論使用Spring的哪種事務管理策略(編程式或者宣告式)事務管理器都是必須的,
- 就是 Spring的核心事務管理抽象,管理封裝了一組獨立于技術的方法,
JDBC事務
<bean id="transactionManager" >
<property name="dataSource" ref="dataSource" />
</bean>
配置好事務管理器后我們需要去配置事務的通知
<!--配置事務通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--配置哪些方法使用什么樣的事務,配置事務的傳播特性-->
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="search*" propagation="REQUIRED"/>
<tx:method name="get" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
spring事務傳播特性:
事務傳播行為就是多個事務方法相互呼叫時,事務如何在這些方法間傳播,spring支持7種事務傳播行為:
- propagation_requierd:如果當前沒有事務,就新建一個事務,如果已存在一個事務中,加入到這個事務中,這是最常見的選擇,
- propagation_supports:支持當前事務,如果沒有當前事務,就以非事務方法執行,
- propagation_mandatory:使用當前事務,如果沒有當前事務,就拋出例外,
- propagation_required_new:新建事務,如果當前存在事務,把當前事務掛起,
- propagation_not_supported:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起,
- propagation_never:以非事務方式執行操作,如果當前事務存在則拋出例外,
- propagation_nested:如果當前存在事務,則在嵌套事務內執行,如果當前沒有事務,則執行與propagation_required類似的操作
Spring 默認的事務傳播行為是 PROPAGATION_REQUIRED,它適合于絕大多數的情況,
假設 ServiveX#methodX() 都作業在事務環境下(即都被 Spring 事務增強了),假設程式中存在如下的呼叫鏈:Service1#method1()->Service2#method2()->Service3#method3(),那么這 3 個服務類的 3 個方法通過 Spring 的事務傳播機制都作業在同一個事務中,
就好比,我們剛才的幾個方法存在呼叫,所以會被放在一組事務當中!
配置AOP
匯入aop的頭檔案!
<!--配置aop織入事務-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.kuang.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
進行測驗
刪掉剛才插入的資料,再次測驗!
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);
}
思考問題?
為什么需要配置事務?
- 如果不配置,就需要我們手動提交控制事務;
- 事務在專案開發程序非常重要,涉及到資料的一致性的問題,不容馬虎!
本文來自博客園,作者:小公羊,轉載請注明原文鏈接:https://www.cnblogs.com/aadzj/p/15312220.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/301406.html
標籤:Java
