spring小结一(五)

2014-11-24 11:07:23 · 作者: · 浏览: 4
行后置通知.
* 后置拦截的类必须实现AfterReturningAdvice接口,实现其中的afterReturning方法.
* 在拦截器中的方法要和checkSecurity方法一样,有两个参数:
JoinPoint point : 可以获得目标方法和参数值
Object val :这里的名字要和return="val"中保持一致,指的是方法的返回值
* 最终通知:
* 注意:最终通知不受异常影响,即不论目标方法执行的过程中是否抛出异常,最终通知都将执行.
* 环绕通知:
* 前后拦截的类必须实现MethodInterceptor接口,实现其中的invoke方法.
* 异常通知:
* 其中throwing指定了传递异常的参数名称
* 在异常通知中(拦截器)中,必须是checkSecurity方法
方法中有两个参数:
JoinPoint point:可以获得方法的名称、参数
Throwable ex : 利用ex.getMessage()可以获得异常信息
* 注解形式
为了在spring配置中使用@AspectJ切面,首先必须启用Spring对@AspectJ切面配置的支持,并确保自动代理
[html]
// 前置通知
/* @Aspectj是按照类型匹配
* @Pointcut用于声明切入点
* 在@AspectJ注解风格的aop中,一个切入点签名通过一个普通的方法来定义
* 1.作为切入点签名的方法必须返回void类型
* 2.方法没有参数用private修饰
* 3.方法体为空
* 切入点表达式的写法
* execution(..)表示匹配方法执行的连接点
* 1."*"表示方法的返回类型任意
* 2.com.liu.service..* 表示service包及其子包中所有的类
* 3.save* 表示类中所有以save开头的方法
* 4.(..)表示参数是任意数量
* @Before 前置通知,在方法调用前执行
* userManagerPointcut() 表示前面定义的切入点
* args 限定匹配特定的连接点(使用spring AOP 的时候方法的执行),其中参数是指定类型的实例
* username1,psw 参数表示指定类型的实例
* 参数名称必须与通知的参数名称一致
* 通知参数的类型必须与目标对象参数的类型一致,如不一致,则拦截不到
*/
@Aspect
public class Security {
@Pointcut("execution(* com.liu.service..*.save*(..))")
private void userManagerPointcut(){}
@Before("userManagerPointcut() && args(username1,psw)")
public void checkSecurity(String username1, String psw){
System.out.println("安全检查"+username1+" "+psw);
}
}
// 后置通知
@Aspect
public class Security {
@Pointcut("execution(* com.liu.service..*.save*(..))")
private void userManagerPointcut(){}
@AfterReturning(pointcut="userManagerPointcut()",returning="value")
public void checkSecurity(String value) {
System.out.println("安全检查"+value);
}
}
// 异常通知
@Aspect
public class Security {
@Pointcut("execution(* com.liu.service..*.save*(..))")
private void userManagerPointcut(){}
@AfterThrowing(pointcut="userManagerPointcut()",throwing="ex")
public void checkSecurity(Exception ex) {
System.out.println("安全检查" + ex);
}
}
// 最终通知
@Aspect
public class Security {
@Pointcut("execution(* com.liu.service..*.save*(..))")
private void userManagerPointcut(){}
@After("userManagerPointcut()")
public void checkSecurity(Exception ex) {
System.out.println("安全检查");
}
}
// 环绕通知
@Aspect
public class Security {
@Pointcut("execution(* com.liu.service..*.save*(..))")
private void userManagerPointcut(){}
@Around("userManagerPointcut()")
public Object checkSecurity(ProceedingJoinPoint point)throw Throwable {
System