Spring笔记(十二)自动代理AspectJ切面
一、声明式通知
- 1、@Before*
- 2、@AfterReturning* a、要获得目标方法的返回值,必须使用returning属性,在@AfterReturning的参数上设置(参数名的绑定),表示向下面方法的哪个参数传入目标方法的返回值。(声明式通知) b、例如:
@AfterReturning(value="execution(* doSome(..))", returning="rtnValue")
public void action(int rtnValue) {
System.out.println(rtnValue);
}
- 3、@AfterThrowing* a、绑订连接点时,必须使用throwing属性 b、例如:
@AfterThrowing(value="execution(* doSome(..))", throwing="ine")
public void actionIllageNameException(IllageNameException ine) {
System.out.println(ine.getMessage());
}
- 4、@After* a、相当于@AfterThrowing和@AfterReturning
- 5、@Around* a、使用ProceedingJoinPoint调用目标对象方法。 b、调用目标方法,应该有返回值
- 6、@DelareParents* a、@DeclareParents(value="aop3.SomeServiceImpl",defaultImpl=OtherServiceImpl.class),声明在新增加接口上。 b、属性value表示对哪个目标类引入。 c、属性defaultImpl表示新增加引入接口逻辑的实现。
@DeclareParents(value="hw.aop.test.SomeServiceImpl", defaultImpl=OtherServiceImpl.class)
private IOtherService service;
IOtherService为新增加方法接口
二、切面 1、切入点表达式:定义切面可以用到哪些目标对象的哪些方法。 2、定义方法,切入点:@Before("XXX"),定义在方法上。 3、在类名上面定义:@Aspect
@Aspect
public class LogAdvice {
@DeclareParents(value="hw.aop.test.SomeServiceImpl", defaultImpl=OtherServiceImpl.class)
private IOtherService service;
}
三、声明式切入点 1、格式:@Pointcut(切入点表达式) 2、execution: a、一个函数,参数为定义的匹配规则,如:@Before("execution(* doSome(..))") b、格式:execution(方法的修饰符? 方法的返回值? 方法名通配符(方法参数)) c、方法参数可以用..,表示任意参数格式数量,也可以指定参数,如int d、方法名可以加上包名,也可以使用通配符。 c、此表达式不支持继承,即父类匹配,切面不织入到子类中。 3、within
四、配置自动代理 1、在配置文件里声明AnnotationAwareAspectJAutoProxyCreator进行自动代理。 2、也可以使用<aop:aspectj-autoproxy />标签自动代理。
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
或
<aop:aspectj-autoproxy />
五、JoinPoint 1、在通知里如果要获得目标方法的名字时,我们可以将方法传入JoinPoint参数。 2、jp.getSignature().getMethodName()获得方法名。
@Before("execution(* doSome(..))")
public void action(JoinPoint jp) {
String mn = jp.getSignature().getMethodName();
System.out.println(mn);
}
:idea: 不错!