主頁 > 軟體設計 > Spring 學習筆記

Spring 學習筆記

2020-11-18 16:35:53 軟體設計

好記憶不如爛筆頭, 能記下點什么, 就記下點什么, 方便后期的鞏固

Spring介紹

Spring 是一個開源框架,是一個分層的 JavaEE 一站式框架,

所謂一站式框架是指 Spring 有 JavaEE 開發的每一層解決方案,

  • WEB層:SpringMVC

  • Service層:Spring的Bean管理,宣告式事務

  • DAO層:Spring的JDBC模板,ORM模板

優點:

  • IOC:方便解耦合

  • AOP:對程式進行擴展

  • 輕量級框架

  • 方便與其他框架整合

Spring使用

Spring開發包解壓后的目錄介紹:

  • docs: Spring 開發規范和API

  • libs: Spring jar 包和源代碼

  • schema: Spring 組態檔的約束

DataAccess 用于資料訪問,WEB 用于頁面顯示,核心容器也就是IOC部分,

控制反轉(IOC)

控制反轉(Inversion of Control)是指將物件的創建權反轉(交給)Spring,

使用IOC就需要匯入IOC相關的包,也就是上圖中核心容器中的幾個包:beans,context,core,expression四個包,

實作原理

傳統方式創建物件:

UserDAO userDAO=new UserDAO();

進一步面向介面編程,可以多型:

UserDAO userDAO=new UserDAOImpl();

這種方式的缺點是介面和實作類高耦合,切換底層實作類時,需要修改源代碼,程式設計應該滿足OCP元祖,在盡量不修改程式源代碼的基礎上對程式進行擴展,此時,可以使用工廠模式:

class BeanFactory{

public static UserDAO getUserDAO(){

return new UserDAOImpl();

}

}

此種方式雖然在介面和實作類之間沒有耦合,但是介面和工廠之間存在耦合,

使用工廠+反射+組態檔的方式,實作解耦,這也是 Spring 框架 IOC 的底層實作,

//xml組態檔

//<bean id="userDAO" class="xxx.UserDAOImpl"></bean>

class BeanFactory{

public static Object getBean(String id){

//決議XML

//反射

Class clazz=Class.forName();

return clazz.newInstance();

}

}

IOC XML 開發

在 docs 檔案中包含了 xsd-configuration.hmtl 檔案,其中定義了 beans schema,

<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 http://www.springframework.org/schema/beans/spring-beans.xsd">

//在此配置bean

<bean id="userService" class="x.y.UserServiceImpl">

</bean>

</beans>

呼叫類:

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");

UserService userService=(UserService)applicationContext.getBean("userService");

userService.save();

IOC 和 DI

DI 指依賴注入,其前提是必須有 IOC 的環境,Spring 管理這個類的時候將類的依賴的屬性注入進來,

例如,在UserServiceImpl.java中:

public class UserServiceImpl implements UserService{

private String name;

public void setName(String name){

this.name=name;

}

public void save(){

System.out.println("save "+name);

}

}

在組態檔中:

<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 http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="userService" class="spring.demo1.UserServiceImpl">

<!--配置依賴的屬性-->

<property name="name" value="tony"/>

</bean>

</beans>

測驗代碼:

@Test

public void demo2(){

//創建Spring工廠

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");

UserService userService=(UserService)applicationContext.getBean("userService");

userService.save();

}

運行結果:

save tony

可以看到,在組態檔中配置的屬性,在 Spring 管理該類的時候將其依賴的屬性成功進行了設定,如果不使用依賴注入,則無法使用介面,只能使用實作類來進行設定,因為介面中沒有該屬性,

Spring 的工廠類

  • BeanFactory: 老版本的工廠類,在呼叫getBean()方法時,才會生成類的實體,

  • ApplicationContext: 在加載組態檔的時候,就會將 Spring 管理的類都實體化,有兩個實作類:

    1. ClassPathXmlApplicationContext: 加載類路徑下的組態檔

    2. FileSystemXmlApplicationContext: 加載磁盤下的組態檔

bean標簽配置

  • id: 唯一約束,不能出現特殊字符

  • name: 理論上可以重復,但是開發中最好不要,可以出現特殊字符

生命周期:

  • init-method: bean被初始化的時候執行的方法

  • destroy-method: bean被銷毀的時候執行的方法

作用范圍:

  • scope: bean的作用范圍,有如下幾種,常用的是前兩種

    • singleton: 默認使用單例模式創建

    • prototype: 多例

    • request: 在web專案中,spring 創建類后,將其存入到 request 范圍中

    • session: 在web專案中,spring 創建類后,將其存入到 session 范圍中

    • globalsession: 在web專案中,必須用在 porlet 環境

屬性注入設定

  1. 構造方法方式的屬性注入: Car 類在構造方法中有兩個屬性,分別為 name 和 price,

<bean id="car" class="demo.Car">

<constructor-arg name="name" value="bmw">

<constructor-arg name="price" value="123">

</bean>

  1. set 方法屬性注入: Employee 類在有兩個 set 方法,分別設定普通型別的 name 和參考型別的 Car (使用 ref 指向參考型別的 id 或 name),

<bean id="employee" class="demo.Employee">

<property name="name" value="xiaoming">

<property name="car" ref="car">

</bean>

  1. P名稱空間的屬性注入: 首先需要引入p名稱空間:

<beans xmlns="http://www.springframework.org/schema/beans"

//引入p名稱空間

xmlns:p="http://www.springframework.org/schema/p"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

如果是普通屬性:

<bean id="car" class="demo.Car" p:name="bmv" p:price="123">

</bean>

如果是參考型別:

<bean id="employee" class="demo.Employee" p:name="xiaoming" p:car-ref:"car">

</bean>

  1. SpEL(Spring Expression Language)屬性注入(Spring 3.x以上版本)

<bean id="car" class="demo.Car">

<property name="name" value="#{'xiaoming'}">

<property name="car" ref="#{car}">

</bean>

  1. 集合型別屬性注入:

<bean id="car" class="demo.Car">

<property name="namelist">

<list>

<value>qirui</value>

<value>baoma</value>

<value>benchi</value>

</list>

</property>

</bean>

多模塊開發配置

  1. 在加載組態檔的時候,加載多個組態檔

  2. 在一個組態檔中引入多個組態檔,通過實作

IOC 注解開發

示例

  1. 引入jar包: 除了要引入上述的四個包之外,還需要引入aop包,

  2. 創建 applicationContext.xml ,使用注解開發引入 context 約束(xsd-configuration.html)

<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/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- bean definitions here -->

</beans>

  1. 組件掃描: 使用IOC注解開發,需要配置組件掃描,也就是哪些包下的類使用IOC的注解,

<context:component-scan base-package="demo1">

  1. 在類上添加注解

  2. 使用注解設定屬性的值

屬性如果有set方法,將屬性注入的注解添加到set方法

屬性沒有set方法,將注解添加到屬性上,

@Component("UserDao")//相當于配置了一個<bean> 其id為UserDao,對應的類為該類

public class UserDAOImpl implements UserDAO {

@Override

public void save() {

// TODO Auto-generated method stub

System.out.println("save");

}

}

注解詳解

  1. @Component

組件注解,用于修飾一個類,將這個類交給 Spring 管理,

有三個衍生的注解,功能類似,也用來修飾類,

  • @Controller:修飾 web 層類

  • @Service:修飾 service 層類

  • @Repository:修飾 dao 層類

2.屬性注入

  • 普通屬性使用 @Value 來設定屬性的值

  • 物件屬性使用 @Autowired ,這個注解是按照型別來進行屬性注入的,如果希望按照 bean 的名稱或id進行屬性注入,需要用 @Autowired 和 @Qualifier 一起使用

  • 實際開發中,使用 @Resource(name=" ") 來進行按照物件的名稱完成屬性注入

3.其他注解

  • @PostConstruct 相當于 init-method,用于初始化函式的注解

  • @PreDestroy 相當于 destroy-method,用于銷毀函式的注解

  • @Scope 作用范圍的注解,常用的是默認單例,還有多例 @Scope("prototype")

IOC 的 XML 和注解開發比較

  • 適用場景:XML 適用于任何場景;注解只適合自己寫的類,不是自己提供的類無法添加注解,

  • 可以使用 XML 管理 bean,使用注解來進行屬性注入

AOP開發

AOP 是 Aspect Oriented Programming 的縮寫,意為面向切面編程,通過預編譯方式和運行期動態代理實作程式功能的統一維護的一種技術,是OOP的延續,

AOP 能夠對程式進行增強,在不修改原始碼的情況下,可以進行權限校驗,日志記錄,性能監控,事務控制等,

也就是說功能分為兩大類,一類是核心業務功能,一類是輔助增強功能,兩類功能彼此獨立進行開發,比如登錄功能是核心業務功能,日志功能是輔助增強功能,如果有需要,將日志和登錄編制在一起,輔助功能就稱為切面,這種能選擇性的、低耦合的把切面和核心業務功能結合的編程思想稱為切面編程,

底層實作

JDK 動態代理只能對實作了介面的類產生代理,Cglib 動態代理可以對沒有實作介面的類產生代理物件,生成的是子類物件,

使用 JDK 動態代理:

public interface UserDao {

public void insert();

public void delete();

public void update();

public void query();

}

實作類:

public class UserDaoImpl implements UserDao { @Override public void insert() { System.out.println("insert"); } @Override public void delete() { System.out.println("delete"); } @Override public void update() { System.out.println("update"); } @Override public void query() { System.out.println("query"); } }

JDK 代理:

public class JDKProxy implements InvocationHandler{

private UserDao userDao;

public JDKProxy(UserDao userDao){

this.userDao=userDao;

}

public UserDao createProxy(){

UserDao userDaoProxy=(UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(),

userDao.getClass().getInterfaces(), this);

return userDaoProxy;

}

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

if("update".equals(method.getName())){

System.out.println("權限校驗");

return method.invoke(userDao, args);

}

return method.invoke(userDao, args);

}

}

通過動態代理增強了 update 函式, 測驗類:

public class Demo1 {

@Test

public void demo1(){

UserDao userDao=new UserDaoImpl();

UserDao proxy=new JDKProxy(userDao).createProxy();

proxy.insert();

proxy.delete();

proxy.update();

proxy.query();

}

}

運行結果為:

insert

delete

權限校驗

update

query

CglibCglib 是第三方開源代碼生成類別庫,可以動態添加類的屬性和方法,

與上邊JDK代理不同,Cglib的使用方式如下:

public class CglibProxy implements MethodInterceptor{

//傳入增強的物件

private UserDao customerDao;

public CglibProxy(UserDao userDao){

this.userDao=userDao;

}

public UserDao createProxy(){

Enhancer enhancer=new Enhancer();

enhancer.setSuperclass(userDao.getClass());

enhancer.setCallback(this);

UserDao proxy=(UserDao)enhancer.create();

return proxy;

}

@Override

public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

if("save".equals(method.getName())){

System.out.println("enhance function");

return methodProxy.invokeSuper(proxy, args);

}

return methodProxy.invokeSuper(proxy, args);

}

}

如果實作了介面的類,底層采用JDK代理,如果不是實作了介面的類,底層采用 Cglib代理,

IOC與傳統方式的比較

  1. 獲取物件方式:傳統通過 new 關鍵字主動創建一個物件,IOC 方式中,將物件的生命周期交給 Spring 管理,直接從 Spring 獲取物件,也就是控制反轉————將控制權從自己手中交到了 Spring 手中,

Spring 的 AOP 開發(AspectJ 的 XML 方式)

AspectJ 是一個 AOP 的框架,Spring 引入 AspectJ,基于 AspectJ 進行 AOP 的開發,

相關術語

  • Joinpoint: 連接點,可以被攔截到的點,也就是可以被增強的方法都是連接點,

  • Pointcut: 切入點,真正被攔截到的點,也就是真正被增強的方法

  • Advice: 通知,方法層面的增強,對某個方法進行增強的方法,比如對 save 方法進行權限校驗,權限校驗的方法稱為通知,

  • Introduction: 引介,類層面的增強,

  • Target: 目標,被增強的物件(類),

  • Weaving: 織入,將 advice 應用到 target 的程序,

  • Proxy: 代理物件,被增強的物件,

  • Aspect: 切面,多個通知和多個切入點的組合,

使用方法

  1. 引入相關包

  2. 引入組態檔

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->

</beans>

  1. 撰寫目標類并配置:

public class ProductDaoImpl implements ProductDao {

@Override

public void save() {

System.out.println("save");

}

@Override

public void update() {

System.out.println("update");

}

@Override

public void find() {

System.out.println("find");

}

@Override

public void delete() {

System.out.println("delete");

}

}

<bean id="productDao" class="demo1.ProductDaoImpl"></bean>

  1. 撰寫切面類,假設用于權限驗證并配置

public class MyAspectXML {

public void checkPri(){

System.out.println("check auth");

}

}

<bean id="myAspect" class="demo1.MyAspectXML"></bean>

  1. 通過AOP配置完成對目標類的增強

<aop:config>

<aop:pointcut expression="execution(* demo1.ProductDaoImpl.save(..))" id="pointcut1"/>

<aop:aspect ref="myAspect">

<aop:before method="chechPri" pointcut-ref="pointcut1"/>

</aop:aspect>

</aop:config>

通知型別

  1. 前置通知:在目標方法執行前操作,可以獲得切入點資訊

<aop:before method="chechPri" pointcut-ref="pointcut1"/>

public void checkPri(JoinPoint joinPoint){

System.out.println("check auth "+joinPoint);

}

  1. 后置通知:在目標方法執行后操作,可以獲得方法回傳值

<aop:after-returning method="writeLog" pointcut-ref="pointcut2" returning="result"/>

public void writeLog(Object result){

System.out.println("writeLog "+result);

}

  1. 環繞通知:在目標方法執行前和后操作,可以阻止目標方法執

<aop:around method="around" pointcut-ref="pointcut3"/>

public Object around(ProceedingJoinPoint joinPoint) throws Throwable{

System.out.println("before");

Object result=joinPoint.proceed();

System.out.println("after");

return result;

}

  1. 例外拋出通知:程式出現例外時操作

<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut4" throwing="ex"/>

public void afterThrowing(Throwable ex){

System.out.println("exception "+ex.getMessage());

}

  1. 最終通知:相當于finally塊,無論代碼是否有例外,都會執行

<aop:after method="finallyFunc" pointcut-ref="pointcut4"/>

public void finallyFunc(){

System.out.println("finally");

}

  1. 引介通知:不常用

Spring 切入點運算式

基于 execution 函式完成

語法:[訪問修飾符] 方法回傳值 包名.類名.方法名(引數)

其中任意欄位可以使用*代替表示任意值

Spring 的 AOP 基于 AspectJ 注解開發

開發步驟

  1. 引入jar包

  2. 設定組態檔:

<?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"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx.xsd">

</beans>

  1. 撰寫配置目標類

<bean id="orderDao" class="demo1.OrderDao"></bean>

public class OrderDao {

public void save(){

System.out.println("save order");

}

public void update(){

System.out.println("update order");

}

public void delete(){

System.out.println("delete order");

}

public void find(){

System.out.println("find order");

}

}

  1. 開啟aop注解自動代理

<aop:aspectj-autoproxy/>

  1. 撰寫切面類并配置

@Aspect

public class MyAspectAnno {

@Before(value="execution(* demo1.OrderDao.save(..))")

public void before(){

System.out.println("before");

}

}

<bean id="myAspect" class="demo1.MyAspectAnno">

注解通知型別

  • @Before: 前置通知

  • @AfterReturning: 后置通知

@AfterReturning(value="execution(* demo1.OrderDao.save(..))",returning="result")

public void after(Object result){

System.out.println("after "+result);

}

  • @Around:環繞通知

@Around(value="execution(* demo1.OrderDao.save(..))")

public Object around(ProceedingJoinPoint joinPoint) throws Throwable{

System.out.println("before");

Object obj=joinPoint.proceed();

System.out.println("after");

return obj;

}

  • @AfterThrowing: 拋出例外

@AfterThrowing(value="execution(* demo1.OrderDao.save(..))",throwing="e")

public void afterThrowing(Throwable e){

System.out.println("exception:"+e.getMessage();

}

  • @After: 最終通知

@After(value="execution(* demo1.OrderDao.save(..))")

public void after(){

System.out.println("finally");

}

  • @PointCut:切入點注解

@PointCut(value="execution(* demo1.OrderDao.save(..))")

private void pointcut1(){}

此時,在上述通知的注解中,value可以替換為該函式名,例如:

@After(value="MyAspect.pointcut1()")

public void after(){

System.out.println("finally");

}

這個注解的好處是,只需要維護切入點即可,不用在修改時修改每個注解,

Spring 的 JDBC 模板

Spring 對持久層也提供了解決方案,也就是 ORM 模塊和 JDBC 的模板,針對 JDBC ,提供了 org.springframework.jdbc.core.JdbcTemplate 作為模板類,

使用 JDBC 模板

  1. 引入jar包,資料庫驅動,Spring 的 jdbc 相關包,

  2. 基本使用:

public void demo1(){

//創建連接池

DriverManagerDataSource dataSource=new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql:///spring4");

dataSource.setUsername("root");

dataSource.setPassword("123456");

//創建JDBC模板

JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);

jdbcTemplate.update("insert into account values (null,?,?)", "xiaoming",1000d);

}

  1. 將連接池和模板交給 Spring 管理

  • 組態檔:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource;">

<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>

<property name="url" value="jdbc:mysql:///spring4"></property>

<property name="username" value="root"></property>

<property name="password" value="123456"></property>

</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate;">

<property name="dataSource" ref="dataSource"></property>

</bean>

  • 測驗檔案:

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration("classpath:applicationContext.xml")

public class JdbcDemo2 {

@Resource(name="jdbcTemplate")

private JdbcTemplate jdbcTemplate;

@Test

public void demo2(){

jdbcTemplate.update("insert into account values (null,?,?)", "xiaolan",1000d);

}

}

使用開源資料庫連接池

  1. 使用 DBCP 的配置:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>

<property name="url" value="jdbc:mysql://192.168.66.128/spring4"></property>

<property name="username" value="root"></property>

<property name="password" value="123456"></property>

  1. 使用 C3P0 的配置:

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

<property name="driverClass" value="com.mysql.jdbc.Driver"></property>

<property name="jdbcUrl" value="jdbc:mysql://192.168.66.128/spring4"></property>

<property name="user" value="root"></property>

<property name="password" value="123456"></property>

</bean>

  1. 引入外部屬性檔案

首先建立外部屬性檔案:

jdbc.driverClass=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://192.168.66.128/spring4

jdbc.username=root

jdbc.password=123456

然后對屬性檔案進行配置:

<context:property-placeholder location="classpath:jdbc.properties"/>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

<property name="driverClass" value="${jdbc.driverClass}"></property>

<property name="jdbcUrl" value="${jdbc.url}"></property>

<property name="user" value="${jdbc.username}"></property>

<property name="password" value="${jdbc.password}"></property>

</bean>

CRUD操作

insert, update, delete 陳述句都借助模板的 update 方法進行操作,

public void demo(){

jdbcTemplate.update("insert into account values (null,?,?)", "xiaoda",1000d);

jdbcTemplate.update("update account set name=?,money=? where id=?", "xiaoda",1000d,2);

jdbcTemplate.update("delete from account where id=?", 6);

}

查詢操作:

public void demo3(){

String name=jdbcTemplate.queryForObject("select name from account where id=?",String.class,5);

long count=jdbcTemplate.queryForObject("select count(*) from account",Long.class);

}

將回傳的結果封裝成為類:

public void demo4(){

Account account=jdbcTemplate.queryForObject("select * from account where id=?", new MyRowMapper(),5);

}

其中:

class MyRowMapper implements RowMapper<Account>{

@Override

public Account mapRow(ResultSet rs, int rowNum) throws SQLException {

Account account=new Account();

account.setId(rs.getInt("id"));

account.setName(rs.getString("name"));

account.setMoney(rs.getDouble("money"));

return account;

}

}

Spring的事務管理

事務

事務是指邏輯上的一組操作,組成這組操作的各個單元,要么全部成功,要么全部失敗,

具有四個特性:

  • 原子性:事務不可分

  • 一致性:事務執行前后資料完整性保持一致

  • 隔離性:一個事務的執行不應該受到其他事務干擾

  • 持久性:一旦事務結束,資料就持久化到資料庫

如果不考慮隔離性會引發安全性問題:

  • 讀問題:

    • 臟讀:一個事務讀到另一個事務未提交的資料

    • 不可重復讀:一個事務讀到另一個事務已經提交的 update 資料,導致一個事務中多次查詢結果不一致

    • 幻讀:一個事務讀到另一個事務已經提交的 insert 資料,導致一個事務中多次查詢結果不一致

  • 寫問題:

    • 丟失更新

解決讀問題:設定事務隔離級別

  • Read uncommitted: 未提交讀,無法解決任何讀問題

  • Read committed: 已提交讀,解決臟讀問題

  • Repeatable read: 重復讀,解決臟讀和不可重復讀問題

  • Serializable:序列化,解決所有讀問題

事務管理API

  1. PlatformTransactionManager: 平臺事務管理器

這是一個介面,擁有多個不同的實作類,如 DataSourceTransactionManager 底層使用了JDBC 管理事務; HibernateTransactionManager 底層使用了 Hibernate 管理事務,

  1. TransactionDefinition: 事務定義資訊

用于定義事務的相關資訊,如隔離級別、超時資訊、傳播行為、是否只讀等

  1. TransactionStatus: 事務的狀態

用于記錄在事務管理程序中,事務的狀態的物件,

上述API的關系: Spring 在進行事務管理的時候,首先平臺事務管理器根據事務定義資訊進行事務管理,在事務管理程序當中,產生各種此狀態,將這些狀態資訊記錄到事務狀態的物件當中,

事務的傳播行為

事務的傳播行為主要解決業務層(Service)方法相互呼叫的問題,也就是不同的業務中存在不同的事務時,如何操作,

Spring 中提供了7種事務的傳播行為,分為三類:

  • 保證多個操作在同一個事務中

    • PROPAGATION_REQUIRED: B方法呼叫A方法,如果A中有事務,使用A中的事務并將B中的操作包含到該事務中;否則新建一個事務,將A和B中的操作包含進來,(默認)

    • PROPAGATION_SUPPORTS:如果A中有事務,使用A的事務;否則不使用事務

    • PROPAGATION_MANDATORY:如果A中有事務,使用A的事務;否則拋出例外

  • 保證多個操作不在同一個事務中

    • PROPAGATION_REQUIRES_NEW:如果A中有事務,將其掛起,創建新事務,只包含自身操作,否則,新建一個事務,只包含自身操作,

    • PROPAGATION_NOT_SUPPORTED:如果A中有事務,掛起,不使用事務,

    • PROPAGATION_NEVER:如果A中有事務,拋出例外,也即不能用事務運行,

  • 嵌套事務

    • PROPAGATION_NESTED:如果A有事務,按照A的事務執行,執行完成后,設定一個保存點,然后執行B的操作,如果出現例外,可以回滾到最初狀態或保存點狀態,

實體

以轉賬為例,業務層的DAO層類如下:

public interface AccountDao {

public void outMoney(String from,Double money);

public void inMoney(String to,Double money);

}

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{

@Override

public void outMoney(String from, Double money) {

this.getJdbcTemplate().update("update account set money = money - ? where name = ?",money,from);

}

@Override

public void inMoney(String to, Double money) {

this.getJdbcTemplate().update("update account set money = money + ? where name = ?",money,to);

}

}

public interface AccountService {

public void transfer(String from,String to,Double money);

}

public class AccountServiceImpl implements AccountService {

private AccountDao accountDao;

public void setAccountDao(AccountDao accountDao) {

this.accountDao = accountDao;

}

@Override

public void transfer(String from, String to, Double money) {

accountDao.outMoney(from, money);

accountDao.inMoney(to, money);

}

}

在xml中進行類的配置:

<bean id="accountService" class="tx.demo.AccountServiceImpl">

<property name="accountDao" ref="accountDao"/>

</bean>

<bean id="accountDao" class="tx.demo.AccountDaoImpl">

<property name="dataSource" ref="dataSource"/>

</bean>

事務管理1: 編程式事務管理

  1. 配置平臺事務管理器

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"></property>

</bean>

  1. 配置事務管理模板類

<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">

<property name="transactionManager" ref="transactionManager"></property>

</bean>

  1. 在業務層注入事務管理模板

<bean id="accountService" class="tx.demo1.AccountServiceImpl">

<property name="accountDao" ref="accountDao"/>

<property name="transactionTemplate" ref="transactionTemplate"/>

</bean>

  1. 編碼實作事務管理

//ServiceImpl類中:

private TransactionTemplate transactionTemplate;

@Override

public void transfer(String from, String to, Double money) {

transactionTemplate.execute(new TransactionCallbackWithoutResult() {

@Override

protected void doInTransactionWithoutResult(TransactionStatus arg0) {

accountDao.outMoney(from, money);

accountDao.inMoney(to, money);

}

});

}

宣告式事務管理(配置實作,基于AOP思想)

  1. XML 方式的宣告式事務管理

  • 配置事務管理器

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"></property>

</bean>

  • 配置事務通知

<tx:advice id="txAdvice" transaction-manager="transactionManager">

<tx:attributes>

<tx:method name="transfer" propagation="REQUIRED"/>

</tx:attributes>

</tx:advice>

  • 配置aop事務

<aop:config>

<aop:pointcut expression="execution(* tx.demo2.AccountServiceImpl.*(..))" id="pointcut1"/>

<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1"/>

</aop:config>

  1. 注解方式

  • 配置事務管理器,和上方一致

  • 開啟事務管理的注解:

<tx:annotation-driven transaction-manager="transactionManager"/>

  • 在使用事務的類上添加一個注解@Transactional

以后還有的內容,再去補充!

文章地址:https://mp.weixin.qq.com/s?__biz=MzU0NTk2MjQyOA==&mid=2247483971&idx=1&sn=cbfb9895543257282f68c8009db23d14&chksm=fb65a290cc122b86891abfcabb67a9fdffe3cb9b9d97ce6572f1e1f3c772b843da30d49ceedf&mpshare=1&scene=23&srcid=0106VNIBwZLqKJLN4B8PbGXY#rd

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/224238.html

標籤:其他

上一篇:11月最新出臺!阿里內部PPT涵蓋研發篇、演算法篇、Java后端架構、spring、微服務、分布式等

下一篇:后端指路手冊(建議收藏):一文告訴你后端都要學習什么?應該從哪里學起!

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 面試突擊第一季,第二季,第三季

    第一季必考 https://www.bilibili.com/video/BV1FE411y79Y?from=search&seid=15921726601957489746 第二季分布式 https://www.bilibili.com/video/BV13f4y127ee/?spm_id_fro ......

    uj5u.com 2020-09-10 05:35:24 more
  • 第三單元作業總結

    1.前言 這應該是本學期最后一次寫作業總結了吧。總體來說,對作業的節奏也差不多掌握了,作業做起來的效率也更高了。雖然和之前的作業一樣,作業中都要用到新的知識,但是相比之前,更加懂得了如何利用工具以及資料。雖然之間卡過殼,但總體而言,這幾次作業還算完成的比較好。 2.作業程序總結 相比前兩個單元,此單 ......

    uj5u.com 2020-09-10 05:35:41 more
  • 北航OO(2020)第四單元博客作業暨課程總結博客

    北航OO(2020)第四單元博客作業暨課程總結博客 本單元作業的架構設計 在本單元中,由于UML圖具有比較清晰的樹形結構,因此我對其中需要進行查詢操作的元素進行了包裝,在樹的父節點中存盤所有孩子的參考。考慮到性能問題,我采用了快取機制,一次查詢后盡可能快取已經遍歷過的資訊,以減少遍歷次數。 本單元我 ......

    uj5u.com 2020-09-10 05:35:48 more
  • BUAA_OO_第四單元

    一、UML決議器設計 ? 先看下題目:第四單元實作一個基于JDK 8帶有效性檢查的UML(Unified Modeling Language)類圖,順序圖,狀態圖分析器 MyUmlInteraction,實際上我們要建立一個有向圖模型,UML中的物件(元素)可能與同級元素連接,也可與低級元素相連形成 ......

    uj5u.com 2020-09-10 05:35:54 more
  • 6.1邏輯運算子

    邏輯運算子 1. && 短路與 運算式1 && 運算式2 01.運算式1為true并且運算式2也為true 整體回傳為true 02.運算式1為false,將不會執行運算式2 整體回傳為false 03.只要有一個運算式為false 整體回傳為false 2. || 短路或 運算式1 || 運算式2 ......

    uj5u.com 2020-09-10 05:35:56 more
  • BUAAOO 第四單元 & 課程總結

    1. 第四單元:StarUml檔案決議 本單元采用了圖模型決議UML。 UML檔案可以抽象為圖、子圖、邊的邏輯結構。 在實作中,圖的節點包括類、介面、屬性,子圖包括狀態圖、順序圖等。 采用了三次遍歷UML元素的方法建圖,第一遍遍歷建點,第二、三次遍歷設定屬性、連邊,實作圖物件的初始化。這里借鑒了一些 ......

    uj5u.com 2020-09-10 05:36:06 more
  • 談談我對C# 多型的理解

    面向物件三要素:封裝、繼承、多型。 封裝和繼承,這兩個比較好理解,但要理解多型的話,可就稍微有點難度了。今天,我們就來講講多型的理解。 我們應該經常會看到面試題目:請談談對多型的理解。 其實呢,多型非常簡單,就一句話:呼叫同一種方法產生了不同的結果。 具體實作方式有三種。 一、多載 多載很簡單。 p ......

    uj5u.com 2020-09-10 05:36:09 more
  • Python 資料驅動工具:DDT

    背景 python 的unittest 沒有自帶資料驅動功能。 所以如果使用unittest,同時又想使用資料驅動,那么就可以使用DDT來完成。 DDT是 “Data-Driven Tests”的縮寫。 資料:http://ddt.readthedocs.io/en/latest/ 使用方法 dd. ......

    uj5u.com 2020-09-10 05:36:13 more
  • Python里面的xlrd模塊詳解

    那我就一下面積個問題對xlrd模塊進行學習一下: 1.什么是xlrd模塊? 2.為什么使用xlrd模塊? 3.怎樣使用xlrd模塊? 1.什么是xlrd模塊? ?python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫。 今天就先來說一下xl ......

    uj5u.com 2020-09-10 05:36:28 more
  • 當我們創建HashMap時,底層到底做了什么?

    jdk1.7中的底層實作程序(底層基于陣列+鏈表) 在我們new HashMap()時,底層創建了默認長度為16的一維陣列Entry[ ] table。當我們呼叫map.put(key1,value1)方法向HashMap里添加資料的時候: 首先,呼叫key1所在類的hashCode()計算key1 ......

    uj5u.com 2020-09-10 05:36:38 more
最新发布
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:20:47 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:20:25 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:20:17 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:20:10 more
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:19:44 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:19:07 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:18:57 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:18:49 more
  • 05單件模式

    #經典的單件模式 public class Singleton { private static Singleton uniqueInstance; //一個靜態變數持有Singleton類的唯一實體。 // 其他有用的實體變數寫在這里 //構造器宣告為私有,只有Singleton可以實體化這個類! ......

    uj5u.com 2023-04-19 08:42:51 more
  • 【架構與設計】常見微服務分層架構的區別和落地實踐

    軟體工程的方方面面都遵循一個最基本的道理:沒有銀彈,架構分層模型更是如此,每一種都有各自優缺點,所以請根據不同的業務場景,并遵循簡單、可演進這兩個重要的架構原則選擇合適的架構分層模型即可。 ......

    uj5u.com 2023-04-19 08:42:41 more