spring AOP就是用AspectJ来实现的,是依赖关系!AspectJ是动态代理的一种实现!spring默认使用的就是AspectJ来实现的动态代理,spring自己的AOP就是使用AspectJ来实现的!
AspectJ是一个面向切面的框架,它扩展了Java语言。AspectJ定义了AOP语法(如:execution(* com.springinaction.springidol.Thinker.thinkofsomething(String)) && args (thoughts)))所以它有一个专门的编译器用来生成遵守Java字节编码规范的Class文件。
AspectJ配置详解:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- 启动对@AspectJ注解的支持 -->
<aop:aspectj-autoproxy />
</beans>
注解切面:
@Aspect
public class MyInterceptor {
@Pointcut("execution (* cn.itcast.service.impl.PersonServiceBean.*(..))")
private void anyMethod() {}//声明一个切点,anyMethod无任何意义,只是供注解依附
@Before("anyMethod() && args(name)")
public void doAccessCheck(String name) {
System.out.println("前置通知:"+ name);
}
@AfterReturning(pointcut="anyMethod()",returning="result")
public void doAfterReturning(String result) {
System.out.println("后置通知:"+ result);
}
@After("anyMethod()")
public void doAfter() {
System.out.println("最终通知");
}
@AfterThrowing(pointcut="anyMethod()",throwing="e")
public void doAfterThrowing(Exception e) {
System.out.println("例外通知:"+ e);
}
//环绕通知
@Around("anyMethod()")
public Object doBasicProfiling(ProceedingJoinPoint joinpoint) throws Throwable {
System.out.println("进入方法");
Object result = joinpoint.proceed();
System.out.println("退出方法");
return result;
}
}
传递参数给所标注的通知
@Aspect
public class Magician implements MindReader{
private String thoughts;
//设置切点参数类型String 和参数thoughts
@Pointcut("execution(* com.springinaction.springidol.Thinker.thinkofsomething(String)) && args(thoughts)")
public void thinking(String thoughts){
}
@Before("Thinking(thoughts)")//拦截切点的参数
public void interceptThoughts(String thoughts){
this.thoughts = thoughts;
}
public String getThoughts(){
return thoughts;
}
}
用注解给切点添加新功能:
@Aspect
public class ContestantIntroducer{
@DeclareParents(
value="com.springinaction.springidol.Performer+",
defaultImpl=GraciousContestant.class)
public static Contestant contestant;
}
Performer是切点,GraciousContestant是新增功能,contestant是接口,GraciousContestant是实现