- XML 中开启Spring 对注解AOP 的⽀持
<!--开启aop注解驱动
proxy-target-class:true强制使用cglib-->
<aop:aspectj-autoproxy/>
- 将applicationContext.xml中配置的AOP一步一步替换成注解
<bean id="logUtil" class="com.tong.utils.LogUtils"></bean>
<aop:config>
<aop:aspect id="logAdvice" ref="LogUtils">
<aop:pointcut id="pt1" expression="execution(* com.tong.edu.service.impl.TransferServiceImpl.*(..))"/>
<aop:before method="beforeMethod" pointcut-ref="pt1"/>
<aop:after-returning method="successMethod" returning="retValue"/>
<aop:around method="arroundMethod" pointcut-ref="pt1"/>
</aop:aspect>
</aop:config>
- 横切逻辑LogUtils替换成功后的注解
package com.tong.utils;
//将XML中的配置Bean-->logUtil替换
@Component
//XML中的<aop:aspect>标签
@Aspect
public class LogUtils {
//声明一个空实现方法,唯一作用就是承载@Pointcut当作切入点
@Pointcut("execution(* com.tong.service.impl.TransferServiceImpl.*(..))")
public void pt1(){
}
/**
* 业务逻辑开始之前执行
*/
//方位信息注解替换<aop:before>标签
@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;
}
}
纯注解模式
在使⽤注解驱动开发aop时,我们要明确的就是,是注解替换掉配置⽂件中的下⾯这⾏配置:
<!--开启aop注解驱动
proxy-target-class:true强制使用cglib-->
<aop:aspectj-autoproxy/>
在配置类中使⽤如下注解进⾏替换上述配置
@Configuration
@ComponentScan("com.tong")
@EnableAspectJAutoProxy //开启spring对注解AOP的⽀持
public class SpringConfiguration {
}