mework.org/schema/aop/spring-aop.xsd">
<!--包扫描-->
<context:component-scan base-package="com.ykq.aop"/>
<!--开启aop切面注解驱动-->
<aop:aspectj-autoproxy/>
</beans>
(4)测试
public class Test {
public static void main(String[] args) {
//加载spring配置文件
ApplicationContext app=new ClassPathXmlApplicationContext("classpath:spring.xml");
MathService mathServiceImpl = (MathService) app.getBean("mathServiceImpl");
System.out.println(mathServiceImpl.add(20, 10));
}
}
使用通配符来统配类路径
@Aspect //标记该类为切面类
@Component //该类对象的创建交于spring容器来管理-----等价于@Service @Controller
public class MyAspect {
//通配符:
/**
* 第一个* : 表示任意修饰符 任意返回类型。
* 第二个* : 表示该包下所有的类。
* 第三个* : 类下所有的方法
* ..: 表示任意参数
*
* 建议包就别使用统配符
*/
@Pointcut(value = "execution(* com.ykq.aop.*.*(..))") //定义为切点
private void mypointcut(){}
@After(value = "mypointcut()")
public void b(){
System.out.println("AAA--->The add method result");
}
}
7.2 注解模式
(1)自定义注解
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "";
}
(2)修改切面类
@Pointcut(value = "@annotation(com.ykq.aop.MyAnnotation)") //定义为切点
private void mypointcut2(){}
//在使用MyAnntation注解的方法之后执行内容
@After(value = "mypointcut2()")
public void b(){
System.out.println("AAA--->The add method result");
}
7.3 aop切面通知的类型
package com.aaa.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect //标记该类为切面类
@Component //该类对象的创建交于spring容器来管理-----等价于@Service @Controller
public class MyAspect {
//通配符:
/**
* 第一个* : 表示任意修饰符 任意返回类型。
* 第二个* : 表示该包下所有的类。
* 第三个* : 类下所有的方法
* ..: 表示任意参数
*
* 建议包就别使用统配符
*/
@Pointcut(value = "execution(* com.ykq.aop.*.*(..))") //定义为切点
private void mypointcut(){}
@Pointcut(value = "@annotation(com.ykq.aop.MyAnnotation)") //定义为切点
private void mypointcut2(){}
// //在使用MyAnntation注解的方法之后执行内容。无论如何都执行。
// @After(value = "mypointcut()")
// public void a(){
// System.out.println("AAA--->The add method result");
// }
//
// //前置通知:
// @Before(value = "mypointcut()")
// public void b(){
// System.out.println("========方法执行前执行切面的内容 前置通知===========");
// }
//
// //后置返回通知. 碰到return. 如果方法出现异常;这种通知不会被执行
// @AfterReturning(value = "mypointcut()",returning = "r") //returnning它会把方法执行的结果赋值给该变量
// public void afterReturning(Object r){ //参数名必须和returning的名称一致
// System.out.println("~~~~~~~~~~~~~~~~~~后置返回通知~~~~~~~~~~~~~~~~"+r);
// }
//
// //异常通知: 当被切入的方法出现异常时,才会执行
// @AfterThrowing(value = "mypointcut()")
// public void afterThrowable(){
// System.out.println("==============异常通知===========================");
// }
//环绕通知。
@Around(value = "mypointcut()")
public Object around(ProceedingJoinPoint joinPoint){//joinPoint:连接点 理解为被执行的方法对象
System.out.println("业务代码执行前执行的内容======================");
try {
Object result = joinPoint.proceed();//执行你的连接点
System.out.println("方法执行完毕后~~~~~~~~~~~~~~~~~&