@AspectJ配置切面
语法基础
- 方法切点函数
- execution()
- @annotation()
- 方法参数切点函数
- args()
- @args()
- 目标类切点函数
- within()
- target()
- @within()
- 目标类切点函数
- @target()
- 代理类切点函数
- this()
通配符
* 匹配任意字符,只匹配一个元素
.. 匹配任意字符,匹配多个元素
+ 匹配指定类,必须跟在类后面,匹配本类以及继承和扩展的所有类
- 支持所有通配符
- execution()
- within()
- 仅支持+通配符
- args()
- this()
- target()
- 不支持通配符
- @args()
- @within()
- @target()
- @annotation()
逻辑运算符
&& || !
and or not
实例
@Aspect
public class PreGreetingAspect {
//增强类型+目标切点表达式
@Before("execution(* greetTo(..))")
//增强所有横切逻辑
public void beforeGreeting(){
System.out.println("How are you");
}
}
public class AspectJProxyTest {
public static void main(String[] args){
AspectJProxyFactory factory = new AspectJProxyFactory(new NativeWaiter());
factory.addAspect(PreGreetingAspect.class);
Waiter proxy = factory.getProxy();
proxy.greetTo("John");
proxy.serveTo("Jhon");
}
}
<!-- 使用@AspectJ注解切面类-->
<bean class="com.smart.aspectj.aspectj.PreGreetingAspect"/>
<!-- 自动代理创建器,将@ApectJ注解切面植入目标Bean中-->
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
<?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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 基于@AspectJ切面的驱动-->
<aop:aspectj-autoproxy/>
<bean id="waiter" class="com.smart.NativeWaiter"/>
<bean class="com.smart.aspectj.aspectj.PreGreetingAspect"/>
</beans>
不同增强类型
- @Before:前置增强,相当于BeforeAdvice
- value
- argNames
- @AfterReturning:后置增强,相当于AfterReturningAdvice
- value
- pointcut
- returning
- argNames
- @Around:环绕增强,相当于MethodInterceptor
- value
- argNames
- @AfterThrowing:抛出增强,相当于ThrowsAdvice
- value
- pointcut
- throwing
- argNames
- @After:Final增强
- value
- argNames
- @DeclareParents:引介增强,相当于IntroductionInterceptor
- value
- defaultImpl