<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.1.12.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
package com.lagou.edu.utils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
/**
* @Author: denghy
* @DateTime: 2021/3/19 11:39
* @Description: TODO
* @package: com.lagou.edu.utils
*/
public class LogUtils {
// @Pointcut("execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))")
// public void pt1(){
//
// }
/**
* 业务逻辑开始之前执行
*/
// @Before("pt1()")
public void beforeMethod(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
System.out.println(arg);
}
System.out.println("业务逻辑开始执行之前执行.......");
}
/**
* 业务逻辑结束时执行(无论异常与否)
*/
// @After("pt1()")
public void afterMethod() {
System.out.println("业务逻辑结束时执行,无论异常与否都执行.......");
}
/**
* 异常时时执行
*/
// @AfterThrowing("pt1()")
public void exceptionMethod() {
System.out.println("异常时执行.......");
}
/**
* 业务逻辑正常时执行
*/
// @AfterReturning(value = "pt1()",returning = "retVal")
public void successMethod(Object retVal) {
System.out.println("业务逻辑正常时执行.......");
}
/**
* 环绕通知
*
*/
/*@Around("pt1()")*/
public Object arroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕通知中的beforemethod....");
Object result = null;
try{
// 控制原有业务逻辑是否执行
// result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
}catch(Exception e) {
System.out.println("环绕通知中的exceptionmethod....");
}finally {
System.out.println("环绕通知中的after method....");
}
return result;
}
}
2、AOP 核?配置
<!-- Spring基于XML的AOP配置前期准备: 在spring的配置?件中加?aop的约束 xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd Spring基于XML的AOP配置步骤: 第?步:把通知Bean交给Spring管理 第?步:使?aop:config开始aop的配置 第三步:使?aop:aspect配置切? 第四步:使?对应的标签配置通知的类型 ??案例采?前置通知,标签为aop:before --> <!--进行aop相关的xml配置,配置aop的过程其实就是把aop相关术语落地--> <!--横切逻辑bean--> <bean id="logUtils" class="com.lagou.edu.utils.LogUtils"></bean> <!--使用config标签表明开始aop配置,在内部配置切面aspect--> <!--aspect = 切入点(锁定方法) + 方位点(锁定方法中的特殊时机)+ 横切逻辑 --> <aop:config> <aop:aspect id="logAspect" ref="logUtils"> <!--切入点锁定我们感兴趣的方法,使用aspectj语法表达式--> <!--<aop:pointcut id="pt1" expression="execution(* *..*.*(..))"/>--> <aop:pointcut id="pt1" expression="execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))"/> <!--方位信息,pointcut-ref关联切入点--> <!--aop:before前置通知/增强--> <aop:before method="beforeMethod" pointcut-ref="pt1"/> <!--aop:after,最终通知,无论如何都执行--> <!--aop:after-returnning,正常执行通知--> <!--<aop:after-returning method="successMethod" returning="retValue"/>--> <!--aop:after-throwing,异常通知--> <!--<aop:around method="arroundMethod" pointcut-ref="pt1"/>--> </aop:aspect> </aop:config>
3、测试类
/**
* 测试xml-anno aop
*/
@Test
public void testXmlAnnoAop() throws Exception {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:beans.xml");
TransferService transferService = applicationContext.getBean(TransferService.class);
transferService.transfer("6029621011000","6029621011001",100);
}
<aop:config proxy-target-class="true">
<!--此标签是基于XML和注解组合配置AOP时的必备标签,表示Spring开启注解配置AOP 的?持--> <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectjautoproxy>
作?:
?于配置前置通知。
出现位置:
它只能出现在aop:aspect标签内部
属性:
method:?于指定前置通知的?法名称
pointcut:?于指定切?点表达式
pointcut-ref:?于指定切?点表达式的引?
-->
<aop:before method="printLog" pointcut-ref="pointcut1"></aop:before>
<!-- 作?: ?于配置正常执?时通知 出现位置: 它只能出现在aop:aspect标签内部 属性: method:?于指定后置通知的?法名称 pointcut:?于指定切?点表达式 pointcut-ref:?于指定切?点表达式的引? --> <aop:after-returning method="afterReturningPrintLog" pointcutref="pt1"></aop:after-returning>
3、异常通知
<!-- 作?: ?于配置异常通知。 出现位置: 它只能出现在aop:aspect标签内部 属性: method:?于指定异常通知的?法名称 pointcut:?于指定切?点表达式 pointcut-ref:?于指定切?点表达式的引? --> <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
<!-- 作?: ?于指定最终通知。 出现位置: 它只能出现在aop:aspect标签内部 属性: method:?于指定最终通知的?法名称 pointcut:?于指定切?点表达式 pointcut-ref:?于指定切?点表达式的引? --> <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
<!-- 作?: ?于配置环绕通知。 出现位置: 它只能出现在aop:aspect标签的内部 属性: method:?于指定环绕通知的?法名称 pointcut:?于指定切?点表达式 pointcut-ref:?于指定切?点表达式的引? --> <aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>
**特别说明**
环绕通知,它是有别于前?四种通知类型外的特殊通知。前?四种通知(前置,后置,异常和最终)它们都是指定何时增强的通知类型。?环绕通知,它是Spring框架为我们提供的?种可以通过编码的
?式,控制增强代码何时执?的通知类型。它??借助的ProceedingJoinPoint接?及其实现类,实现?动触发切?点?法的调?。
**ProceedingJoinPoint接?介绍
1、bean.xml
<!--开启aop注解驱动 proxy-target-class:true强制使用cglib --> <aop:aspectj-autoproxy/>
2、logUtil
package com.lagou.edu.utils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @Author: denghy
* @DateTime: 2021/3/19 11:39
* @Description: TODO
* @package: com.lagou.edu.utils
*/
@Component //替代 <bean id="logUtils" class="com.lagou.edu.utils.LogUtils"></bean>
@Aspect //替代 <aop:aspect id="logAspect" ref="logUtils">
public class LogUtils {
/*<aop:pointcut id="pt1" expression="execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))"/>*/
@Pointcut("execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))")
public void pt1(){
}
/**
* 业务逻辑开始之前执行
*/
@Before("pt1()")
public void beforeMethod(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
System.out.println(arg);
}
System.out.println("业务逻辑开始执行之前执行.......");
}
/**
* 业务逻辑结束时执行(无论异常与否)
*/
@After("pt1()")
public void afterMethod() {
System.out.println("业务逻辑结束时执行,无论异常与否都执行.......");
}
/**
* 异常时时执行
*/
@AfterThrowing("pt1()")
public void exceptionMethod() {
System.out.println("异常时执行.......");
}
/**
* 业务逻辑正常时执行
*/
@AfterReturning(value = "pt1()",returning = "retVal")
public void successMethod(Object retVal) {
System.out.println("业务逻辑正常时执行.......");
}
/**
* 环绕通知
*
*/
@Around("pt1()")
public Object arroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕通知中的beforemethod....");
Object result = null;
try{
// 控制原有业务逻辑是否执行
System.out.println("环绕通知中的控制原有业务逻辑是否执行....");
result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
}catch(Exception e) {
System.out.println("环绕通知中的exceptionmethod....");
}finally {
System.out.println("环绕通知中的after method....");
}
return result;
}
}
3、测试
在配置类上
@EnableAspectJAutoProxy
/*转出账户减钱*/
update account set money=money-100 where name=‘a’;
/**转?账户加钱*/
update account set money=money+100 where name=‘b’;
public interface PlatformTransactionManager {
/* 获取事务状态信息
*/
TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
throws TransactionException;
/**
* 提交事务
*/
void commit(TransactionStatus status) throws TransactionException;
/**
* 回滚事务
*/
void rollback(TransactionStatus status) throws TransactionException; }
1、添加依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.12.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.1.12.RELEASE</version> </dependency>
2、bean.xml配置
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd "> <!--开启注解扫描,base-package指定扫描的包路径--> <context:component-scan base-package="com.lagou.edu"/> <!--引入外部资源文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--第三方jar中的bean定义在xml中--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg name="dataSource" ref="dataSource"/> </bean> <!--spring声明式事务配置,声明式事务无非就是配置一个aop,只不过有些标签不一样罢了--> <!--横切逻辑--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <constructor-arg name="dataSource" ref="dataSource"></constructor-arg> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 定制事务细节,传播行为、隔离级别等 --> <tx:attributes> <!-- 一般性配置--> <tx:method name="*" read-only="false" propagation="REQUIRED" isolation="DEFAULT" timeout="-1"/> <!--针对查询的覆盖性配置--> <tx:method name="query*" read-only="true" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <aop:config> <!--advice-ref指向增强=横切逻辑+方位--> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.lagou.edu.service.impl.TransferServiceImpl.*(..))"/> </aop:config> </beans>
3、测试
事务得到控制
1.beans.xml配置文件
<!--spring声明式事务配置,声明式事务无非就是配置一个aop,只不过有些标签不一样罢了--> <!--横切逻辑--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <constructor-arg name="dataSource" ref="dataSource"></constructor-arg> </bean> <!--开启spring对注解事务的?持--> <tx:annotation-driven transaction-manager="transactionManager"/> <!--<tx:advice id="txAdvice" transaction-manager="transactionManager"> <!– 定制事务细节,传播行为、隔离级别等 –> <tx:attributes> <!– 一般性配置–> <tx:method name="*" read-only="false" propagation="REQUIRED" isolation="DEFAULT" timeout="-1"/> <!–针对查询的覆盖性配置–> <tx:method name="query*" read-only="true" propagation="SUPPORTS"/> </tx:attributes> </tx:advice>
2、业务实现类添加注解
@Transactional
@EnableTransactionManagement//开启spring注解事务的?持
public class SpringConfiguration {
}
spring--第三部分:Spring Aop应用与源码分析(一)
原文:https://www.cnblogs.com/denghy-301/p/14595502.html