Spring中xml和注解方式使用AOP

AOP是面向切面的编程。使用AOP的方式可以减少代码直接的耦合,后期维护起来较为方便。先看看最普通的Spring项目来配置AOP。

需要的Jar包

Spring需要的Jarspring-core.xx.jar,spring-beans.xx.jar,spring-context.xx.jar,spring-context-support.xx.jar,spring-expression.xx.jar

AOP需要的包:spring-aop.xx.jar,spring-aspects.xx.jar,aopalliance.xx.jar,aspectjrt.jar,aspectjweaver.jar

XML方式

  1. 配置好通知类,Spring的基础内容
  2. 使用xml
<aop:config>
		<aop:aspect id="time" ref="timeHandler1">
			<!-- 前置通知 -->
                <aop:before method="printStartTime" pointcut="execution(* com.xx.service.*.*(..))"/>
			<!-- 后置通知 -->
                <aop:after method="printEndTime" pointcut="execution(* com.xx.service.*.*(..))"/>
		</aop:aspect>
</aop:config>

至此,切入成功。

注解方式

  1. 在XML中开启AOP的自动代理(SpringBoot中默认开启的)
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  1. 在类上注解@Aspect表示切面
  2. 在方法上注释@Before@After表示前置/后置通知。@Before("AOP表达式")

定义切入点

@Before@After中的表达式一样时,可以定义一个空的方法,作为切入点

@Asspect
public LogHandler{
    @PointCut("execution ...")
	public void pointTest(){}
	@Before("pointTest()") // @PointCut定义方法的名字
    public void printStartTime(){
        // ...
    }
    @After("pointTest()")
    public void printEndTime(){
        // ...
    }
}

环绕通知

@Aspect
public class TimeHandler {
	@Around("execution(* com.xx.service.*.*(..))")
	public void aroundTime(ProceedingJoinPoint pjp) {
		System.out.println("环绕通知-->前");
		try {
			// 业务逻辑通过proceed()方法执行,相当于嵌入到这来
			pjp.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		System.out.println("环绕通知-->后");
	}
}
原文地址:https://www.cnblogs.com/to-red/p/12013578.html