@Aspect:
AspectJProxyFactory
这个类可以通过解析 @Aspect 标注的类来生成代理aop代理对象——手动Aop的方式之一。实现代理的步骤如下:
@Pointcut(“execution(表达式1(表达式2))”)
?
—— com可选*
——任意值..
——任意参数execution(* com..*(..))
——com所有子包中的所有方法execution(* * *(..))
——所有方法execution(* t*(..))
——所有以t开头的方法springboot项目导入依赖:
org.projectlombok lombok true org.aspectj aspectjweaver org.springframework.boot spring-boot-starter-test test
切面:
@Aspect
@Slf4j
public class LogAop {@Pointcut("execution(* com..*(..))")public void mate() {};@Before("mate()")public void before(JoinPoint joinPoint) {log.info("======> 前置处理方法 <=====");log.info("切入点: =====>" + joinPoint);}@AfterReturning(pointcut = "mate()", returning = "returnValue")public void afterReturn(JoinPoint joinPoint, Object returnValue) {log.info("======> 后置处理方法 <=====");log.info("切入点: =====>" + joinPoint);log.info("返回值: =====>" + returnValue);}}
被代理对象:
package com.cj.aop;import java.math.BigDecimal;public class AopTestMd {public String add(BigDecimal a, BigDecimal b) {return a.add(b).setScale(4, BigDecimal.ROUND_HALF_UP).toString();}public void sub(BigDecimal a, BigDecimal b) {System.out.println(a.subtract(b).setScale(4, BigDecimal.ROUND_HALF_UP).toString());}
}
测试类:
public class LogAopTestMd {@Testpublic void testAop() {// 代理的目标对象AopTestMd target = new AopTestMd();// 构建 AspectJProxyFactory 对象AspectJProxyFactory proxyFactory = new AspectJProxyFactory();// 设置被代理的目标对象proxyFactory.setTarget(target);// 设置标注了@Aspect注解的类proxyFactory.addAspect(LogAop.class);// 生成代理对象AopTestMd proxy = proxyFactory.getProxy();proxy.add(new BigDecimal("3.14"), new BigDecimal(0.5099));proxy.sub(new BigDecimal(4.00), new BigDecimal(1));}
}
输出:
在实际开发环境中,因为springboot的自动装配,我们完全不用去管AspectJProxyFactory
对象的生成与代理对象的生成的过程,只需要写好切面并注册到容器中就可以了。只需要给切面类加上@Configuration或者@Component。
@Aspect
@Component
@Slf4j
public class LogAop {@Pointcut("execution(* com..*(..))")public void mate() {};@Before("mate()")public void before(JoinPoint joinPoint) {log.info("======> 前置处理方法 <=====");log.info("切入点: =====>" + joinPoint);}@AfterReturning(pointcut = "mate()", returning = "returnValue")public void afterReturn(JoinPoint joinPoint, Object returnValue) {log.info("======> 后置处理方法 <=====");log.info("切入点: =====>" + joinPoint);log.info("返回值: =====>" + returnValue);}}