事务问题
转账例子:
Account sourceAccount = accountDao.findByName(sourceName);
Account targetAccount = accountDao.findByName(targetName);
sourceAccount.setMoney(sourceAccount.getMoney()-money);
targetAccount.setMoney(targetAccount.getMoney()+money);
accountDao.UpdateAccount(sourceAccount);
accountDao.UpdateAccount(targetAccount);
若其中出现错误,会造成严重后果,虽然会提交,但他会把每一次操作看成是一次事务。
所以我们用到了ThreadLocal,将Connection传入其中,这里写一个ConnectionUtils:
public class ConnectionUtils {
private ThreadLocal<Connection> tl=new ThreadLocal<>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
//获取当前线程上的连接
public Connection getThreadConnection(){
try {
//先从ThreadLocal上获取
Connection conn=tl.get();
//判断当前线程上是否有链接
if (conn==null) {
//从数据源中获取一个连接,并存入ThreadLocal中
conn=dataSource.getConnection();
tl.set(conn);
}
//返回当前线程上的连接
return conn;
}catch (Exception e){
throw new RuntimeException(e);
}
}
public void removeConnection(){
tl.remove();
}
}
再写一个事务类,有开启事务、提交事务回滚事务、释放连接:
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
//开启事务
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//提交事务
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//回滚事务
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//释放连接
public void release(){
try {
connectionUtils.getThreadConnection().close();//还回连接池中
connectionUtils.removeConnection();//解绑ThreadLocal和Connection
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
最终转账方法变成了:
public void transfer(String sourceName, String targetName, double money) {
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
Account sourceAccount = accountDao.findByName(sourceName);
Account targetAccount = accountDao.findByName(targetName);
sourceAccount.setMoney(sourceAccount.getMoney()-money);
targetAccount.setMoney(targetAccount.getMoney()+money);
accountDao.UpdateAccount(sourceAccount);
accountDao.UpdateAccount(targetAccount);
//3.提交事务
txManager.commit();
} catch (Exception e) {
//回滚事务
txManager.rollback();
e.printStackTrace();
}finally {
//释放资源
txManager.release();
}
}
还需要挺多配置,如dao中的获取连接和xml的配置。我们会发现,这样会非常的麻烦,若服务有很多方法,要每个方法中都加上事务,还要写好多类,配置很多。
动态代理
特点: 字节码随用随创建,随用随加载
作用: 不修改源码的基础上对方法增强
分类:
- 基于接口的动态代理
- 基于子类的动态代理
基于接口的动态代理:
涉及的类:Proxy
如何创建代理对象:
使用Proxy中的newProxyInstance方法
创建代理对象的要求:
被代理类最少实现一个接口,如果没有则不能用
newProxyInstance方法的参数:
- ClassLoader:类加载器:加载代理对象字节码的。和被代理对象使用相同的类加载器,固定写法。
- Class[]:字节码数组:用于让代理对象和被代理对象有相同的方法。固定写法。
- InvocationHandler:用于提供增强的代码:通常情况下都是匿名内部类,但不必须
基于子类的动态代理
涉及的类:Enhancer(第三方cglib库)
如何创建代理对象:
使用Enhancer中的create方法
创建代理对象的要求:
被代理类不能是最终类
create方法的参数:
- Class:用于指定被代理对象的字节码。
- Callback:用于提供增强的代码:通常情况下都是匿名内部类,但不必须。我们一般写的都是该接口的子接口的实行类:MethodIntercepetor
所以上面的转账可加一个动态代理,以做到事务管理的一种方法增强:
public class BeanFactory {
private AccountService accountService;
private TransactionManager txManager;
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public final void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
public AccountService getAccountService() {
AccountService as = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
accountService.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue = null;
//添加事务的支持
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
rtValue = method.invoke(accountService, args);
//3.提交事务
txManager.commit();
//4.返回结果
return rtValue;
} catch (Exception e) {
//回滚事务
txManager.rollback();
throw new RuntimeException(e);
} finally {
//释放资源
txManager.release();
}
}
});
return as;
}
}
xml:
<bean id="proxyAccountService" factory-bean="beanFactory" factory-method="getAccountService"></bean>
<bean id="beanFactory" class="cn.huangyy.factory.BeanFactory">
<property name="accountService" ref="accountService"></property>
<property name="txManager" ref="txManager"></property>
</bean>
AOP
Aspect Oriented Programming 面向切面编程
通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。可利用AOP对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
作用:
在程序运行期间,不修改源码对已有的方法进行增强。
优势:
- 减少重复代码
- 提高开发效率
- 维护方便
AOP相关术语:
- Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。通俗说就是业务和增强方法的连接口。
- Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。通俗点说就是被增强的。
- Adive(增强/通知):所谓通知是指拦截到Joinponit之后要做的事就是通知。类型:前置通知、后置通知、异常通知、最终通知、环绕通知。
- Introduction(引介):引介是一种特殊的通知,在不修改类代码的前提下,Introduction可以在运行期为类动态地添加一些方法或Field
- Target(目标对象):代理的目标对象
- Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。Spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。
- Proxy(代理):一个类被AOP织入增强后,就产出一个结果代理类
- Aspect(切面):是切入点和通知(引介)的结合。
xml配置aop
例:
-
1.把通知bean交给spring来管理
-
2.配置AOP 。
aop:config
-
3.使用
aop:aspect
标签配置切面- id属性:给切面提供一个唯一标志
- ref属性:指定通知类bean的id
-
4.我们如今是让printLog在切入点方法执行之前执行,则前置通知
aop:before
- method属性:指定logger类哪个方法是前置通知
- pointcut属性:指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
-
5.切入点表达式的写法:
- 关键字:execution(表达式)
- 表达式:访问修饰符 返回值 包名.包名.包名…类名.方法名(参数列表)例:
public void cn.huangyy.service.impl.AccountService.saveAccount()
- 细节:访问修饰符可以省略
- 可以使用通配符
*
来标识,如* cn.huangyy.service.impl.AccountService.saveAccount()
- 可以使用…表示当前包及其子包,如
* *..AccountService.saveAccount()
- 可以使用
*
来标识类名及方法名,如* *..*.*()
- 参数列表:基本类型直接写名称,引用写
包名.类名
的方式。可用*则必须有参数,使用…则有无参数都可 - 全通配写法
* *..*.*(..)
<?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 id="accountService" class="cn.huangyy.service.impl.AccountServiceImpl"></bean>
<!--把通知bean也交给spring来管理-->
<bean id="logger" class="cn.huangyy.utils.Logger"></bean>
<!--配置AOP.aop:config-->
<aop:config>
<!--使用aop:aspect标签配置切面
id属性:给切面提供一个唯一标志
ref属性:指定通知类bean的id
-->
<aop:aspect id="logAdvice" ref="logger">
<!--我们如今是让printLog在切入点方法执行之前执行,则前置通知aop:before
method属性:指定logger类哪个方法是前置通知
pointcut属性:指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
切入点表达式的写法:
关键字:execution(表达式)
表达式:访问修饰符 返回值 包名.包名.包名...类名.方法名(参数列表)
例:public void cn.huangyy.service.impl.AccountService.saveAccount()
-->
<aop:before method="printLog" pointcut="execution(public void cn.huangyy.service.impl.AccountServiceImpl.saveAccount())"></aop:before>
</aop:aspect>
</aop:config>
</beans>
通知类型:
- 前置通知:
aop:before
- 后置通知:
aop:after-returning
- 异常通知:
aop:after-throwing
- 最终通知:
aop:after
配置切入点表达式:
可用aop:pointcut
- id属性:用于指定表达式的唯一标志
- expression属性:用于指定表达式内容
- 细节:写在切面内只能在切面内用,还可写在aop:aspect前面,让所有切面可用
例:
<!--前置通知-->
<aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>
<!--后置通知-->
<aop:after-returning method="afterPrintLog" pointcut-ref="pt1"></aop:after-returning>
<!--异常通知-->
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
<!--最终通知-->
<aop:after method="endPrintLog" pointcut-ref="pt1"></aop:after>
<!--配置切入点表达式 id属性用于指定表达式的唯一标志,expression属性用于指定表达式内容-->
<aop:pointcut id="pt1" expression="execution(* cn.huangyy.service.impl.*.*(..))"/>
环绕通知
aop:around
当我们配置了环绕通知之后,切入点方法没有执行,对比动态代理中的环绕代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用
Spring框架为我们提供了一个接口:ProceedingJoinPoint
。
该接口有个方法proceed()
,此方法就明确调用切入点方法。该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
例子:
xml:
<aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>
方法:
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue=null;
try {
Object[] args=pjp.getArgs();//得到方法所需的参数
System.out.println("前置");
rtValue=pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("后置");
return rtValue;
} catch (Throwable t) {
System.out.println("异常");
throw new RuntimeException(t);
}finally {
System.out.println("最终");
}
}
注解的AOP
xml中:
- context:component-scan:注解会扫描的范围
- aop:aspectj-autoproxy:配置spring开启注解AOP的支持
切面类:
- @Aspect:表示当前类是一个切面类
- @Pointcut:配置切入点表达式(写个空方法即可)
- @Before:前置通知
- @AfterReturning:后置通知
- @AfterThrowing:异常通知
- @After:最终通知
- @Around:环绕通知
例:
@Component("logger")
@Aspect
public class Logger {
@Pointcut("execution(* cn.huangyy.service.impl.*.*(..))")
private void pt1(){}
@Before("pt1()")
public void beforePrintLog(){
System.out.println("Logger中的--before开始记录日志了。。。");
}
@AfterReturning("pt1()")
public void afterPrintLog(){
System.out.println("Logger中的--after开始记录日志了。。。");
}
@AfterThrowing("pt1()")
public void afterThrowingPrintLog(){
System.out.println("Logger中的--异常开始记录日志了。。。");
}
@After("pt1()")
public void endPrintLog(){
System.out.println("Logger中的--最终开始记录日志了。。。");
}
//@Around("pt1()")
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue=null;
try {
Object[] args=pjp.getArgs();//得到方法所需的参数
System.out.println("前置");
rtValue=pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("后置");
return rtValue;
} catch (Throwable t) {
System.out.println("异常");
throw new RuntimeException(t);
}finally {
System.out.println("最终");
}
}
}
Spring中的事务控制
- 需要spring-tx和jdbc的jar包
- 配置事务管理器
- 配置事务的通知(此时需要导入事务的约束,tx和aop的)。 使用
tx:advice
标签配置事务控制- 属性:
- id:给事务通知起唯一标志
- transaction-manager:给事务通知提供一个事务管理器
- 配置事务的属性
tx:attributes
及其中的tx:method
- 属性:
- isolation:用于指定事务的隔离级别,默认值是default,表示使用数据库的隔离级别
- propagation:用于指定事务的传播行为。默认值为Required,表示一定会有事务,增删改的选择。查询方法可是选择Supports
- read-only:用于指定事务是否只读,只有查询方法才能设置为true。默认值为false,表示读写。
- timeout:用于指定事务的超时时间,默认为-1,永不超时。如果指定了数值,则以秒为单位
- rollback-for:用于指定一个异常,当产生异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示都回滚
- rollback-for:用于指定一个异常,当产生异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,表示都回滚
- 配置AOP的切入点表达式
- 建立事务通知和切入点表达式的对应关系
aop:advisor
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务的通知(此时需要导入事务的约束,tx和aop的)-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--配置事务的属性-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<!--配置AOP的切入点表达式-->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* cn.huangyy.service.impl.*.*(..))"/>
<!--建立事务通知和切入点表达式的对应关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
基于注解的事务控制
- 配置事务管理器
- 开启spring对注解事务的支持
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
- 在需要事务支持的地方使用
@Transactional
注解