你絕對(duì)需要了解的Spring學(xué)習(xí)筆記

作者:Java架構(gòu)研究室

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

Spring簡(jiǎn)介

Spring 是一個(gè)開(kāi)源框架,是一個(gè)分層的 JavaEE 一站式框架。

所謂一站式框架是指 Spring 有 JavaEE 開(kāi)發(fā)的每一層解決方案。

WEB層:SpringMVC

Service層:Spring的Bean管理,聲明式事務(wù)

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

優(yōu)點(diǎn):

IOC:方便解耦合

AOP:對(duì)程序進(jìn)行擴(kuò)展

輕量級(jí)框架

方便與其他框架整合

Spring使用

Spring開(kāi)發(fā)包解壓后的目錄介紹:

docs: Spring 開(kāi)發(fā)規(guī)范和API

libs: Spring jar 包和源代碼

schema: Spring 配置文件的約束


DataAccess 用于數(shù)據(jù)訪問(wèn),WEB 用于頁(yè)面顯示,核心容器也就是IOC部分。

控制反轉(zhuǎn)(IOC)

控制反轉(zhuǎn)(Inversion of Control)是指將對(duì)象的創(chuàng)建權(quán)反轉(zhuǎn)(交給)Spring。

使用IOC就需要導(dǎo)入IOC相關(guān)的包,也就是上圖中核心容器中的幾個(gè)包:beans,context,core,expression四個(gè)包。

實(shí)現(xiàn)原理

傳統(tǒng)方式創(chuàng)建對(duì)象:

UserDAO userDAO=new UserDAO();

進(jìn)一步面向接口編程,可以多態(tài):

UserDAO userDAO=new UserDAOImpl();

這種方式的缺點(diǎn)是接口和實(shí)現(xiàn)類高耦合,切換底層實(shí)現(xiàn)類時(shí),需要修改源代碼。程序設(shè)計(jì)應(yīng)該滿足OCP元祖,在盡量不修改程序源代碼的基礎(chǔ)上對(duì)程序進(jìn)行擴(kuò)展。此時(shí),可以使用工廠模式:

class BeanFactory{

? ? public static UserDAO getUserDAO(){

? ? ? ? return new UserDAOImpl();

? ? }

}

此種方式雖然在接口和實(shí)現(xiàn)類之間沒(méi)有耦合,但是接口和工廠之間存在耦合。

使用工廠+反射+配置文件的方式,實(shí)現(xiàn)解耦,這也是 Spring 框架 IOC 的底層實(shí)現(xiàn)。

//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 開(kāi)發(fā)

在 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>

調(diào)用類:

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

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

userService.save();

IOC 和 DI

DI 指依賴注入,其前提是必須有 IOC 的環(huán)境,Spring 管理這個(gè)類的時(shí)候?qū)㈩惖囊蕾嚨膶傩宰⑷脒M(jìn)來(lái)。

例如,在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">

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

? ? </bean>

</beans>

測(cè)試代碼:

@Test

public void demo2(){

//創(chuàng)建Spring工廠

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

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

userService.save();

}

運(yùn)行結(jié)果:

save tony

可以看到,在配置文件中配置的屬性,在 Spring 管理該類的時(shí)候?qū)⑵湟蕾嚨膶傩猿晒M(jìn)行了設(shè)置。如果不使用依賴注入,則無(wú)法使用接口,只能使用實(shí)現(xiàn)類來(lái)進(jìn)行設(shè)置,因?yàn)榻涌谥袥](méi)有該屬性。

Spring 的工廠類

BeanFactory: 老版本的工廠類,在調(diào)用getBean()方法時(shí),才會(huì)生成類的實(shí)例。

ApplicationContext: 在加載配置文件的時(shí)候,就會(huì)將 Spring 管理的類都實(shí)例化。有兩個(gè)實(shí)現(xiàn)類:

ClassPathXmlApplicationContext: 加載類路徑下的配置文件

FileSystemXmlApplicationContext: 加載磁盤(pán)下的配置文件

bean標(biāo)簽配置

id: 唯一約束,不能出現(xiàn)特殊字符

name: 理論上可以重復(fù),但是開(kāi)發(fā)中最好不要??梢猿霈F(xiàn)特殊字符

生命周期:

init-method: bean被初始化的時(shí)候執(zhí)行的方法

destroy-method: bean被銷毀的時(shí)候執(zhí)行的方法

作用范圍:

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

singleton: 默認(rèn)使用單例模式創(chuàng)建

prototype: 多例

request: 在web項(xiàng)目中,spring 創(chuàng)建類后,將其存入到 request 范圍中

session: 在web項(xiàng)目中,spring 創(chuàng)建類后,將其存入到 session 范圍中

globalsession: 在web項(xiàng)目中,必須用在 porlet 環(huán)境

屬性注入設(shè)置

構(gòu)造方法方式的屬性注入: Car 類在構(gòu)造方法中有兩個(gè)屬性,分別為 name 和 price。

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

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

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

</bean>

set 方法屬性注入: Employee 類在有兩個(gè) set 方法,分別設(shè)置普通類型的 name 和引用類型的 Car (使用 ref 指向引用類型的 id 或 ?name)。

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

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

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

</bean>

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>

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

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

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

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

</bean>

集合類型屬性注入:

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

? ? <property name="namelist">

? ? ? ? <list>

? ? ? ? ? ? <value>qirui</value>

? ? ? ? ? ? <value>baoma</value>

? ? ? ? ? ? <value>benchi</value>

? ? ? ? </list>

? ? </property>

</bean>

多模塊開(kāi)發(fā)配置

在加載配置文件的時(shí)候,加載多個(gè)配置文件

在一個(gè)配置文件中引入多個(gè)配置文件,通過(guò)實(shí)現(xiàn)

IOC 注解開(kāi)發(fā)

示例

引入jar包: 除了要引入上述的四個(gè)包之外,還需要引入aop包。

創(chuàng)建 applicationContext.xml ,使用注解開(kāi)發(fā)引入 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>

組件掃描: 使用IOC注解開(kāi)發(fā),需要配置組件掃描,也就是哪些包下的類使用IOC的注解。

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

在類上添加注解

使用注解設(shè)置屬性的值

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

屬性沒(méi)有set方法,將注解添加到屬性上。

@Component("UserDao")//相當(dāng)于配置了一個(gè)<bean> 其id為UserDao,對(duì)應(yīng)的類為該類

public class UserDAOImpl implements UserDAO {

@Override

public void save() {

// TODO Auto-generated method stub

System.out.println("save");

}

}

注解詳解

@Component

組件注解,用于修飾一個(gè)類,將這個(gè)類交給 Spring 管理。

有三個(gè)衍生的注解,功能類似,也用來(lái)修飾類。

@Controller:修飾 web 層類

@Service:修飾 service 層類

@Repository:修飾 dao 層類

2.屬性注入

普通屬性使用 @Value 來(lái)設(shè)置屬性的值

對(duì)象屬性使用 @Autowired ?,這個(gè)注解是按照類型來(lái)進(jìn)行屬性注入的。如果希望按照 bean 的名稱或id進(jìn)行屬性注入,需要用 @Autowired 和 @Qualifier 一起使用

實(shí)際開(kāi)發(fā)中,使用 @Resource(name=" ") 來(lái)進(jìn)行按照對(duì)象的名稱完成屬性注入

3.其他注解

@PostConstruct 相當(dāng)于 init-method,用于初始化函數(shù)的注解

@PreDestroy 相當(dāng)于 destroy-method,用于銷毀函數(shù)的注解

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

IOC 的 XML 和注解開(kāi)發(fā)比較

適用場(chǎng)景:XML 適用于任何場(chǎng)景;注解只適合自己寫(xiě)的類,不是自己提供的類無(wú)法添加注解。

可以使用 XML 管理 bean,使用注解來(lái)進(jìn)行屬性注入

AOP開(kāi)發(fā)

AOP 是 Aspect Oriented Programming 的縮寫(xiě),意為面向切面編程,通過(guò)預(yù)編譯方式和運(yùn)行期動(dòng)態(tài)代理實(shí)現(xiàn)程序功能的統(tǒng)一維護(hù)的一種技術(shù),是OOP的延續(xù)。

AOP 能夠?qū)Τ绦蜻M(jìn)行增強(qiáng),在不修改源碼的情況下,可以進(jìn)行權(quán)限校驗(yàn),日志記錄,性能監(jiān)控,事務(wù)控制等。

也就是說(shuō)功能分為兩大類,一類是核心業(yè)務(wù)功能,一類是輔助增強(qiáng)功能。兩類功能彼此獨(dú)立進(jìn)行開(kāi)發(fā)。比如登錄功能是核心業(yè)務(wù)功能,日志功能是輔助增強(qiáng)功能,如果有需要,將日志和登錄編制在一起。輔助功能就稱為切面,這種能選擇性的、低耦合的把切面和核心業(yè)務(wù)功能結(jié)合的編程思想稱為切面編程。

底層實(shí)現(xiàn)

JDK 動(dòng)態(tài)代理只能對(duì)實(shí)現(xiàn)了接口的類產(chǎn)生代理。Cglib 動(dòng)態(tài)代理可以對(duì)沒(méi)有實(shí)現(xiàn)接口的類產(chǎn)生代理對(duì)象,生成的是子類對(duì)象。

使用 JDK 動(dòng)態(tài)代理:

public interface UserDao {

public void insert();

public void delete();

public void update();

public void query();

}

實(shí)現(xiàn)類:

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("權(quán)限校驗(yàn)");

return method.invoke(userDao, args);

}

return method.invoke(userDao, args);

}

}

通過(guò)動(dòng)態(tài)代理增強(qiáng)了 update 函數(shù)。 測(cè)試類:

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();

}

}

運(yùn)行結(jié)果為:

insert

delete

權(quán)限校驗(yàn)

update

query

CglibCglib 是第三方開(kāi)源代碼生成類庫(kù),可以動(dòng)態(tài)添加類的屬性和方法。

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

public class CglibProxy implements MethodInterceptor{

//傳入增強(qiáng)的對(duì)象

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);

}

}

如果實(shí)現(xiàn)了接口的類,底層采用JDK代理。如果不是實(shí)現(xiàn)了接口的類,底層采用 Cglib代理。

IOC與傳統(tǒng)方式的比較

獲取對(duì)象方式:傳統(tǒng)通過(guò) new 關(guān)鍵字主動(dòng)創(chuàng)建一個(gè)對(duì)象。IOC 方式中,將對(duì)象的生命周期交給 Spring 管理,直接從 Spring 獲取對(duì)象。也就是控制反轉(zhuǎn)————將控制權(quán)從自己手中交到了 Spring 手中。

Spring 的 AOP 開(kāi)發(fā)(AspectJ 的 XML 方式)

AspectJ 是一個(gè) AOP 的框架,Spring 引入 AspectJ,基于 AspectJ 進(jìn)行 AOP 的開(kāi)發(fā)。

相關(guān)術(shù)語(yǔ)

Joinpoint: 連接點(diǎn),可以被攔截到的點(diǎn)。也就是可以被增強(qiáng)的方法都是連接點(diǎn)。

Pointcut: 切入點(diǎn),真正被攔截到的點(diǎn),也就是真正被增強(qiáng)的方法

Advice: 通知,方法層面的增強(qiáng)。對(duì)某個(gè)方法進(jìn)行增強(qiáng)的方法,比如對(duì) save 方法進(jìn)行權(quán)限校驗(yàn),權(quán)限校驗(yàn)的方法稱為通知。

Introduction: 引介,類層面的增強(qiáng)。

Target: 目標(biāo),被增強(qiáng)的對(duì)象(類)。

Weaving: 織入,將 advice 應(yīng)用到 target 的過(guò)程。

Proxy: 代理對(duì)象,被增強(qiáng)的對(duì)象。

Aspect: 切面,多個(gè)通知和多個(gè)切入點(diǎn)的組合。

使用方法

引入相關(guān)包

引入配置文件

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

編寫(xiě)目標(biāo)類并配置:

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>

編寫(xiě)切面類,假設(shè)用于權(quán)限驗(yàn)證并配置

public class MyAspectXML {

public void checkPri(){

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

}

}

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

通過(guò)AOP配置完成對(duì)目標(biāo)類的增強(qiáng)

通知類型

前置通知:在目標(biāo)方法執(zhí)行前操作,可以獲得切入點(diǎn)信息

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

public void checkPri(JoinPoint joinPoint){

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

}

后置通知:在目標(biāo)方法執(zhí)行后操作,可以獲得方法返回值

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

public void writeLog(Object result){

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

}

環(huán)繞通知:在目標(biāo)方法執(zhí)行前和后操作,可以阻止目標(biāo)方法執(zhí)行

<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;

}

異常拋出通知:程序出現(xiàn)異常時(shí)操作

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

public void afterThrowing(Throwable ex){

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

}

最終通知:相當(dāng)于finally塊,無(wú)論代碼是否有異常,都會(huì)執(zhí)行

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

public void finallyFunc(){

System.out.println("finally");

}

引介通知:不常用

Spring 切入點(diǎn)表達(dá)式

基于 execution 函數(shù)完成

語(yǔ)法:[訪問(wèn)修飾符] 方法返回值 包名.類名.方法名(參數(shù))

其中任意字段可以使用*代替表示任意值

Spring 的 AOP 基于 AspectJ 注解開(kāi)發(fā)

開(kāi)發(fā)步驟

引入jar包

設(shè)置配置文件:

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

編寫(xiě)配置目標(biāo)類

<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");

}

}

開(kāi)啟aop注解自動(dòng)代理

<aop:aspectj-autoproxy/>

編寫(xiě)切面類并配置

@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:環(huán)繞通知

@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:切入點(diǎn)注解

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

private void pointcut1(){}

此時(shí),在上述通知的注解中,value可以替換為該函數(shù)名,例如:

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

public void after(){

System.out.println("finally");

}

這個(gè)注解的好處是,只需要維護(hù)切入點(diǎn)即可,不用在修改時(shí)修改每個(gè)注解。

Spring 的 JDBC 模板

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

使用 JDBC 模板

引入jar包,數(shù)據(jù)庫(kù)驅(qū)動(dòng),Spring 的 jdbc 相關(guān)包。

基本使用:

public void demo1(){

? ? //創(chuàng)建連接池

DriverManagerDataSource dataSource=new DriverManagerDataSource();

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

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

dataSource.setUsername("root");

dataSource.setPassword("123456");

//創(chuàng)建JDBC模板

JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);

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

}

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

配置文件:

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

測(cè)試文件:

@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);

}

}

使用開(kāi)源數(shù)據(jù)庫(kù)連接池

使用 DBCP 的配置:

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

使用 C3P0 的配置:

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

引入外部屬性文件

首先建立外部屬性文件:

jdbc.driverClass=com.mysql.jdbc.Driver

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

jdbc.username=root

jdbc.password=123456

然后對(duì)屬性文件進(jìn)行配置:

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

CRUD操作

insert, update, delete 語(yǔ)句都借助模板的 update 方法進(jìn)行操作。

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);

}

將返回的結(jié)果封裝成為類:

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的事務(wù)管理

事務(wù)

事務(wù)是指邏輯上的一組操作,組成這組操作的各個(gè)單元,要么全部成功,要么全部失敗。

具有四個(gè)特性:

原子性:事務(wù)不可分

一致性:事務(wù)執(zhí)行前后數(shù)據(jù)完整性保持一致

隔離性:一個(gè)事務(wù)的執(zhí)行不應(yīng)該受到其他事務(wù)干擾

持久性:一旦事務(wù)結(jié)束,數(shù)據(jù)就持久化到數(shù)據(jù)庫(kù)

如果不考慮隔離性會(huì)引發(fā)安全性問(wèn)題:

讀問(wèn)題:

臟讀:一個(gè)事務(wù)讀到另一個(gè)事務(wù)未提交的數(shù)據(jù)

不可重復(fù)讀:一個(gè)事務(wù)讀到另一個(gè)事務(wù)已經(jīng)提交的 update 數(shù)據(jù),導(dǎo)致一個(gè)事務(wù)中多次查詢結(jié)果不一致

幻讀:一個(gè)事務(wù)讀到另一個(gè)事務(wù)已經(jīng)提交的 insert 數(shù)據(jù),導(dǎo)致一個(gè)事務(wù)中多次查詢結(jié)果不一致

寫(xiě)問(wèn)題:

丟失更新

解決讀問(wèn)題:設(shè)置事務(wù)隔離級(jí)別

Read uncommitted: 未提交讀,無(wú)法解決任何讀問(wèn)題

Read committed: 已提交讀,解決臟讀問(wèn)題

Repeatable read: 重復(fù)讀,解決臟讀和不可重復(fù)讀問(wèn)題

Serializable:序列化,解決所有讀問(wèn)題

事務(wù)管理API

PlatformTransactionManager: 平臺(tái)事務(wù)管理器

這是一個(gè)接口,擁有多個(gè)不同的實(shí)現(xiàn)類,如 DataSourceTransactionManager 底層使用了JDBC 管理事務(wù); HibernateTransactionManager 底層使用了 Hibernate 管理事務(wù)。

TransactionDefinition: 事務(wù)定義信息

用于定義事務(wù)的相關(guān)信息,如隔離級(jí)別、超時(shí)信息、傳播行為、是否只讀等

TransactionStatus: 事務(wù)的狀態(tài)

用于記錄在事務(wù)管理過(guò)程中,事務(wù)的狀態(tài)的對(duì)象。

上述API的關(guān)系: Spring 在進(jìn)行事務(wù)管理的時(shí)候,首先平臺(tái)事務(wù)管理器根據(jù)事務(wù)定義信息進(jìn)行事務(wù)管理,在事務(wù)管理過(guò)程當(dāng)中,產(chǎn)生各種此狀態(tài),將這些狀態(tài)信息記錄到事務(wù)狀態(tài)的對(duì)象當(dāng)中。

事務(wù)的傳播行為

事務(wù)的傳播行為主要解決業(yè)務(wù)層(Service)方法相互調(diào)用的問(wèn)題,也就是不同的業(yè)務(wù)中存在不同的事務(wù)時(shí),如何操作。

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

保證多個(gè)操作在同一個(gè)事務(wù)中

PROPAGATION_REQUIRED: B方法調(diào)用A方法,如果A中有事務(wù),使用A中的事務(wù)并將B中的操作包含到該事務(wù)中;否則新建一個(gè)事務(wù),將A和B中的操作包含進(jìn)來(lái)。(默認(rèn))

PROPAGATION_SUPPORTS:如果A中有事務(wù),使用A的事務(wù);否則不使用事務(wù)

PROPAGATION_MANDATORY:如果A中有事務(wù),使用A的事務(wù);否則拋出異常

保證多個(gè)操作不在同一個(gè)事務(wù)中

PROPAGATION_REQUIRES_NEW:如果A中有事務(wù),將其掛起,創(chuàng)建新事務(wù),只包含自身操作。否則,新建一個(gè)事務(wù),只包含自身操作。

PROPAGATION_NOT_SUPPORTED:如果A中有事務(wù),掛起,不使用事務(wù)。

PROPAGATION_NEVER:如果A中有事務(wù),拋出異常,也即不能用事務(wù)運(yùn)行。

嵌套事務(wù)

PROPAGATION_NESTED:如果A有事務(wù),按照A的事務(wù)執(zhí)行,執(zhí)行完成后,設(shè)置一個(gè)保存點(diǎn),然后執(zhí)行B的操作。如果出現(xiàn)異常,可以回滾到最初狀態(tài)或保存點(diǎn)狀態(tài)。

實(shí)例

以轉(zhuǎn)賬為例,業(yè)務(wù)層的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中進(jìn)行類的配置:

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

事務(wù)管理1: 編程式事務(wù)管理

配置平臺(tái)事務(wù)管理器

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

</bean>

配置事務(wù)管理模板類

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

</bean>

在業(yè)務(wù)層注入事務(wù)管理模板

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

</bean>

編碼實(shí)現(xiàn)事務(wù)管理

//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);

}

});

}

聲明式事務(wù)管理(配置實(shí)現(xiàn),基于AOP思想)

XML 方式的聲明式事務(wù)管理

配置事務(wù)管理器

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

</bean>

配置事務(wù)通知

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

</tx:advice>

配置aop事務(wù)

<aop:config>

</aop:config>

注解方式

配置事務(wù)管理器,和上方一致

開(kāi)啟事務(wù)管理的注解:

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

在使用事務(wù)的類上添加一個(gè)注解@Transactional

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 今天,騎著電動(dòng)車漫無(wú)目的的在城市郊區(qū)靠近鄉(xiāng)村的路上行走,路邊的枯草叢里冒出了星星點(diǎn)點(diǎn)的綠,還有杏樹(shù)的枝...
    舒雁閱讀 387評(píng)論 0 2
  • 2018年的第一場(chǎng)雪比2016年來(lái)得早一些!2016年1月31日那天雪花紛飛,水溫4.5度。我迎來(lái)了冬泳的...
    天蝎妮閱讀 849評(píng)論 8 6
  • 時(shí)間真是一個(gè)奇怪的東西,可以用來(lái)衡量世間的所有,毫無(wú)夸張。年少時(shí)期待可以早些長(zhǎng)成大人,以為就有美好的風(fēng)景,時(shí)值之時(shí)...
    李譯閱讀 973評(píng)論 2 16

友情鏈接更多精彩內(nèi)容