目录
什么是aop?
把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的
基础上,对我们的已有方法进行增强。
import org.aspectj.lang.ProceedingJoinPoint;
public class AopMethod {
public void before() {
System.out.println("前置通知");
}
public void afterReturning() {
System.out.println("后置通知");
}
public void afterThrowing() {
System.out.println("异常通知");
}
/**
* 环绕通知需要环绕通知的前置通知执行完成后,让原有的方法执行,再执行环绕通知的后置通知
*/
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕通知-前置");
//执行原来的方法
joinPoint.proceed();
System.out.println("环绕通知-后置");
}
public void after() {
System.out.println("最终通知");
}
}
applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="ceshi" class="com.alvin.service.Ceshi"/>
<bean id="aopmethod" class="com.alvin.aop.AopMethod"/>
<aop:config>
<aop:aspect ref="aopmethod">
<aop:before method="before" pointcut="execution(* com.alvin.service.*.m*(..))"/>
<aop:after-returning method="afterReturning" pointcut="execution(* com.alvin.service.*.m*(..))"/>
<aop:around method="around" pointcut="execution(* com.alvin.service.*.m*(..))"/>
<aop:after method="after" pointcut="execution(* com.alvin.service.*.m*(..))"/>
</aop:aspect>
</aop:config>
</beans>
springmvc.xml
<!--配置开启AOP的注解使用@EnableAspectJAutoProxy-->
<aop:aspectj-autoproxy/>
@Component
@Aspect
public class AopMethod {
@Before("execution(* com.alvin.service.Ceshi.method())")
public void before() {
System.out.println("前置通知");
}
}
或者配置config
原文:https://www.cnblogs.com/birdofparadise/p/10012297.html