使用注解實作宣告式事務 1.jar包 spring-tx-4.3.9.RELEASE mysql-connector-java-5.1.47.jar common-dbcp.jar 連接池使用資料源 common-pool.jar 連接池 spring-jdbc-4.3.9.RELEASE aopalliance.jar 2.配置 增加事務tx的命名空間,
<!--配置資料庫相關-事務-->
<bean id="dataSource" >
<property name="driverClassName" value="https://www.cnblogs.com/ghlz/p/com.mysql.jdbc.Driver"></property>
<property name="url" value="mysql://127.0.0.1:3306/springDB"></property>
<property name="username" value="https://www.cnblogs.com/ghlz/p/root"></property>
<property name="password" value="https://www.cnblogs.com/ghlz/p/123456"></property>
<property name="maxActive" value="https://www.cnblogs.com/ghlz/p/10"></property>
<property name="maxIdle" value="https://www.cnblogs.com/ghlz/p/6"></property>
</bean>
<!--配置事務管理器txManager-->
<bean id="txManager" >
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--增加對事務的支持-->
<tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>
3.使用
將需要成為事務的方法前增加注解,
@Transactional(readOnly = false,propagation = Propagation.REQUIRED)
面向切面編程——AOP


<!--addStudent()所在的方法-->
<bean id="studentService" >
<property name="studentDao" ref="studentDao"></property>
</bean>
<!--“前置通知”類-->
<!--======連接線的一方======-->
<bean id="logBefore" >
</bean>
<!--將addStudent()與通知相連-->
<aop:config>
<!--配置切入點(在哪里執行通知)-->
<!--=====連接線的另一方======-->
<aop:pointcut expression="execution(public void org.ghl.service.StudentServiceImpl.addStudent(org.ghl.entity.Student)) or execution
(public void org.ghl.service.StudentServiceImpl.deleteStudentByNo(int))" id="pointcut"></aop:pointcut>
<!--advisor相當于連接切入點和切面的線-->
<!--=======連接線=======-->
<aop:advisor advice-ref="logBefore" pointcut-ref="pointcut"/>
</aop:config>
(3)撰寫
實作介面: public class LogBefore implements MethodBeforeAdvice
運算式expression常見示例

public void afterThrowing(Method method,Object[] args,Object target, Throwable ex){}
環繞通知實作步驟:
可以獲得目標方法的全部控制權,
(1)通public class LogAround implements MethodInterceptor { @Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = null;
//方法體1
try {
//方法體2
System.out.println("用環繞實作【前置通知】...");
//invocation.proceed();前為前置通知
result=invocation.proceed();//控制目標方法的執行
//result就是目標方法addStudent()的回傳值
//invocation.proceed();后為后置通知
System.out.println("用環繞實作【后置通知】...");
System.out.println("用環繞實作后置通知:目標物件:"+invocation.getThis()+",呼叫的方法名:"+invocation.getMethod().getName()+",方法的引數個數:"+
invocation.getArguments().length+",方法的回傳值:"+result);
} catch (Exception ex) {
//方法體3
// 例外通知
System.out.println("用環繞實作【例外通知】...");
}
return result;
}
}
(2)業務類
(3)配置 使用環繞通知時,目標方法的一切資訊可以通過innovation引數獲取到, 環繞通知底層通過攔截器實作,轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/158654.html
標籤:Java
下一篇:Json欄位選取器介紹和實作
