@Pointcut("execution(* com.zjl.transfer.service.impl.*.*(..))")
private void p1(){
}
@Around("com.zjl.transfer.utils.LoggerUtils.p1()")
public static void aroundPrintLog(ProceedingJoinPoint pjp){
try {
System.out.println("aroungPrintLog开始记录日志,before");
pjp.proceed();
System.out.println("aroundPrintLog结束记录日志,after");
} catch (Throwable e) {
System.out.println("aroundPrintLog异常记录日志,exception");
e.printStackTrace();
}finally{
System.out.println("aroundPrintLog最终记录日志,finally");
}
}
aopalliance-1.0.jar
aspectjweaver-1.8.7.jar
spring-aop-4.2.4.RELEASE.jar
spring-aspects-4.2.4.RELEASE.jar
b、引入aop名称空间
<?xml version="1.0"encoding="UTF-8"?>
<beansxmlns="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">
<beans/>
<bean id="loggerAdvice" class="com.zjl.spring.Logger"></bean>
- <!-- 配置AOP:配置切面和连接点之间的关系 -->
<aop:config>
<!-- 配置切面 ref指定的通知对象的引用 -->
<aop:aspect ref="loggerAdvice">
<!-- 配置前置通知 :before是前置通知。 method:指定的是哪个方法是前置通知方法
pointcut:指定的哪些连接点将变成切入点。需要使用的是切入点表达式。
写法:execution(表达式)
例如:
public void com.zjl.spring.UserServiceImpl.saveUser()
pointcut-ref:引用定义好的公用的切入点
-->
<aop:before method="printLog"
pointcut="execution(public void com.zjl.spring.UserServiceImpl.saveUser())"/></aop:aspect>
</aop:config>
execution:匹配方法的执行(常用)
execution(public * *(..))
基本语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))
within:匹配包或子包中的方法(了解)
within(com.zjl.aop..*)
this:匹配实现接口的代理对象中的方法(了解)
this(com.zjl.aop.user.UserDAO)
target:匹配实现接口的目标对象中的方法(了解)
target(com.zjl.aop.user.UserDAO)
args:匹配参数格式符合标准的方法(了解)
args(int,int)
Spring支持使用如下三个逻辑运算符来组合切入点表达式:
&&:要求连接点同时匹配两个切点表达式
||:要求连接点匹配至少一个切入点表达式
!:要求连接点不匹配指定的切入点表达式
a、导入aop的jar包
和xml配置导入的包相同。
b、导入aop和context名称空间
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
c、开启Spring对AspectJ的支持
<context:component-scan base-package="com.zjl"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>