切面(Aspect)是Spring AOP的核心,它是与特定连接点相关的一系列通知和增强的集合。在Spring AOP中,切面可以使用常规类(通常是具有一组特殊方法的JavaBean)或使用注释来实现。切面可以包含以下类型的通知:前置通知(Before advice)、后置通知(After advice)、返回通知(After returning advice)、异常通知(After throwing advice)和环绕通知(Around advice)。
下面是一个使用XML配置的切面的例子:
<aop:config>
<!-- 配置切点,即在哪些方法用到增强,后面是表达式 -->
<aop:pointcut id="mypointCut" expression="execution( void com.bipt.ServiceAop.impl.ImplUserService.save())"/>
<!-- 配置切面,切面就是通知加上增强 -->
<aop:aspect id="myadvice" ref="Advice">
<!-- before表示前置通知,在切点执行之前执行,method则是通知里的一种方法 -->
<aop:before method="advice1" pointcut-ref="mypointCut"></aop:before>
</aop:aspect>
</aop:config>
@Aspect
@Component
public class LogAspect {
@Pointcut("execution(* com.example.demo.controller.*.*(..))")
public void log() {}
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
// 前置通知
}
@After("log()")
public void doAfter(JoinPoint joinPoint) {
// 后置通知
}
@AfterReturning(returning = "result", pointcut = "log()")
public void doAfterReturning(Object result) {
// 返回通知
}
@AfterThrowing(throwing = "e", pointcut = "log()")
public void doAfterThrowing(Exception e) {
// 异常通知
}
@Around("log()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// 环绕通知
return proceedingJoinPoint.proceed();
}
}