使用AspectJ实现AOP
1.首先什么是AspectJ
AspectJ是使用面向切面的一个框架
它扩展了Java语言(它本身也是一种语言)
支持原生Java代码 有自己的编译器 将代码翻译成Java字节码文件
是为了方便编写AOP代码而出现的
使用AOP编程的三个重点 通知 切点 织入
2.使用AspectJ实现AOP方式一: xml配置完成AOP
(1.创建通知类 添加需要的方法(前置 后置 环绕 Returning throwing)
public class MyAdvice {
public void before() {
System.out.println("前置");
}
public void after() {
System.out.println("后置");
}
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前");
Object result = pjp.proceed();
System.out.println("环绕后");
return result;
}
public void returning() {
System.out.println("After returning 后置");
}
public void throwing() {
System.out.println("发生异常了");
}
(2.在配置文件中添加通知类的bean
(3.添加<aop:config>添加子标签
<!-- 准备通知对象 -->
<bean name="abc" class="com.lanou.advice.MyAdvice"></bean>
<!-- 创建切入点 -->
<aop:config>
<aop:pointcut expression="execution(* com.lanou.DaoImpl.*.*(..))" id="pc"/>
<!-- 织入 -->
<aop:aspect ref="abc">
<!-- 按照顺序写方法 前 环绕 后 -->
<aop:before method="before" pointcut-ref="pc"/>
<aop:around method="around" pointcut-ref="pc"/>
<aop:after method="after" pointcut-ref="pc"/>
<aop:after-returning method="returning" pointcut-ref="pc"/>
<aop:after-throwing method="throwing" pointcut-ref="pc"/>
</aop:aspect>
</aop:config>
3.使用注解配置完成AOP
(1.创建通知类
(2.添加@Aspect 设置通知类
(3.创建切点方法
@Aspect
@Component
public class MyAdvice_annotion {
@Pointcut("execution(* com.lanou.DaoImpl.*.*(..))")
public void point() {}
@Before("point()")
public void before() {
System.out.println("前置");
}
@After("point()")
public void after() {
System.out.println("后置");
}
@Around("point()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前");
Object result = pjp.proceed();
System.out.println("环绕后");
return result;
}
@AfterReturning("point()")
public void returning() {
System.out.println("After returning 后置");
}
@AfterThrowing("point()")
public void throwing() {
System.out.println("发生异常了");
}
}
最后在Spring的配置文件中添加:
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
可以理解为:告诉Spring是使用@aspectJ和注解的方式实现AOP