概念解析:
JoinPoint:连接点 业务逻辑与切面的切点
PointCut:连接点集合
Aspect:切面@Aspect 切面上的逻辑
Advice:在连接点上的建议 或者切面上的业务逻辑 可以理解成为@Before等
Target:被代理对象
Weave:织入
Annotation主要步骤:
a) 加上对应的xsd文件spring-aop.xsd
b) applicationContext.xml加语句 <aop:aspectj-autoproxy/>
c) 此时就可以解析对应的Annotation了
d) 建立我们的拦截类 LogInterceptor
e) 用@Aspect注解这个类
f) 建立处理方法
g) 用@Before来注解方法
h) 写明白切入点(execution …….)
i) 让spring对我们的拦截器类进行管理@Component
applicationContext.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:component-scan base-package="com.mth"/>
<!-- 设定自动匹配aop设置 自动产生代理-->
<aop:aspectj-autoproxy/>
</beans>
定义一个LogInterceptor类:
package com.mth.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
*
* @ClassName: LogInterceptor
* @Description: Aop 面像切面编程 此类也要交给Spring初始化就需要添加注解@Component
* @author mth 75100313@qq.com
* @date 2014-1-20 上午08:44:19
*
*/
@Aspect
@Component
public class LogInterceptor {
// 多个一样的植入点可以抽出来定义
@Pointcut("execution(public void com.mth.impl..*.*(..))")
public void myMethod() {
}
// 在方法执行之前先要执行这个方法
// 植入点语句
@Before("execution(public void com.mth.impl.StuDaoImpl.save*(com.mth.bean.Student))")
public void before() {
System.out.println("before save");
}
// 方法正常执行完成之后(参数就是方法名)
@AfterReturning("myMethod()")
public void afterReturning() {
System.out.println("after save");
}
// 方法抛异常之后执行(StuDaoImpl里面的保存学生方法)
@AfterThrowing("myMethod()")
public void afterThrowing() {
System.out.println("afterThrowing");
}
// 环绕方法
@Around("myMethod()")
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("around save start");
pjp.proceed();
System.out.println("arround save end");
}
// 最终通知 任意返回值类型 com.mth下的任意包中的任意类中的任意方法 参数任意
@After("execution(* com.mth..*.*(..))")
public void afterMethod() {
System.out.println("---------after----------");
}
}