1、横切逻辑类配置
@Component
@Aspect
public class LogUtil {
@Pointcut("execution(public void deppon.service.AccountServiceImpl.transfer(java.lang.String,java.lang.String,int))")
public void info(){
}
@Before("info()")
public void beforeMethod(JoinPoint joinPoint){
System.out.println("方法执行之前执行......");
Object[] args = joinPoint.getArgs();
for(Object arg:args){
System.out.println(arg);
}
System.out.println("方法执行之前执行......");
}
//@After("info()")
public void afterMethod(){
System.out.println("方法执行之后执行......");
}
// @AfterThrowing("info()")
public void exceptionMethod(){
System.out.println("异常方法执行之后执行......");
}
// @AfterReturning("info()")
public void finallyMethod(){
System.out.println("finally执行......");
}
// @Around("info()")
public Object surroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("事务开始!!!");
Object returnValue = null;
try{
returnValue = joinPoint.proceed();
} catch (Exception throwable) {
throwable.printStackTrace();
System.out.println("事务回滚!!!");
throw throwable;
}
System.out.println("事务提交!!!");
return returnValue;
}
}
2-1、xml配置
<aop:aspectj-autoproxy/>
2-2、将 xml 配置替换成注解配置,在实例 bean上添加注解:@EnableAspectJAutoProxy
本文展示了如何使用SpringAOP来实现横切逻辑,包括定义切点(@Pointcut),前置通知(@Before),后置通知(@After),异常通知(@AfterThrowing),返回通知(@AfterReturning)以及环绕通知(@Around)。例子中详细展示了如何处理方法执行前后的操作,以及事务管理。同时,文章对比了XML配置和注解配置的方式。
1389

被折叠的 条评论
为什么被折叠?



