方法一:使用原声spring API接口
创建一个类去继承
before增强方法继承MethodBeforeAdvice类,实现抽象方法。
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//args:参数
//target:目标对象
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
after增强方法继承AfterReturningAdvice类,实现抽象方法
public class AfterLog implements AfterReturningAdvice {
//returnValue;返回值
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为"+returnValue);
}
}
XML定义切入点,使增强方法作用于切入点
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点:experssion:表达式,execution(要执行的位置!*****)-->
<aop:pointcut id="pointcut" expression="execution(* com.LL.sp7.*.*(..))"/>
<!--执行环绕增加!-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
方法二:自定义类实现增强
自定义增强类
public class DiyPointCut {
public void before(){
System.out.println("======方法执行前======");
}
public void after(){
System.out.println("======方法执行后======");
}
}
XML定义切点,定义增强方法
<aop:config>
<!--自定义切面,ref要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.LL.sp7.UserService.*(..))"/>
<!--通知-->
<!--设置在切入点之前-->
<aop:before method="before" pointcut-ref="point"/>
<!--设置在切入点之后-->
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
方法三:注解
直接在增强方法上定义切入点
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.LL.sp7.UserService.*(..))")
public void before(){
System.out.println("======方法执行之前==========");
}
}
XML开启注解支持
<!--开启注解支持 JDK(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy proxy-target-class="false" />