Spring AOP doc link
spring aop中,编译的过程中把切面直接写入代理对象中。而不是在类加载时对类进行操作。
相关概念描述
- Aspect 切面,含有业务逻辑切入其他类的模块
- Join point 连接点,可以加入逻辑的地方
- Advice 通知,切面接入连接点的动作,分around, before,after
- Pointcut 切点,通过切点表达式所切入的点,连接点的子集
- Introduction 引入 把方法或变量引入目标对象中
- Target object 目标对象,一个被切面通知的类
- Weaving 织入,将切面和目标对象联系起来,创建新类的过程
切面的使用
- 引入spring-aop包后,在application中加入切面扫描
<aop:aspectj-autoproxy/>
- 使用@Aspect定义切面
@Aspect
public class NotVeryUsefulAspect {
}
- 使用注解护额切点表达式定义切点
@Pointcut("execution(public * *(..))")
private void anyPublicOperation() {}
@Pointcut("within(com.xyz.someapp.trading..*)")
private void inTrading() {}
@Pointcut("anyPublicOperation() && inTrading()")
private void tradingOperation() {}
// check return
@AfterReturning(
pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
returning="retVal")
public void doAccessCheck(Object retVal) {}
// advice to run only when exceptions of a given type are thrown
@AfterThrowing(
pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()"
,throwing="ex")
public void doRecoveryActions(DataAccessException ex) {}
// After advice must be prepared
// to handle both normal and exception return conditions
@After("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
// do work both before and after the method executes and to
// determine when, how, and even if the method actually
// gets to execute at all.
// note : first parameter of the advice method must be of type ProceedingJoinPoint
@Around("com.xyz.myapp.SystemArchitecture.businessService()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
return retVal;
}
public void doReleaseLock() {}
// Any join point where
// the proxy implements the AccountService interface:
@Pointcut("this(com.xyz.service.AccountService)")
private void accountServiceThisAop() {}
// Any join point where
// the target object implements the AccountService interface:
@Pointcut("this(com.xyz.service.AccountService)")
private void accountServiceTargateAop() {}
- Advice Parameters 通知时的参数
通过JoinPoint获取
- getArgs(): Returns the method arguments.
- getThis(): Returns the proxy object.
- getTarget(): Returns the target object.
- getSignature(): Returns a description of the method that is being advised.
- toString(): Prints a useful description of the method being advised.
@Pointcut("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)")
private void accountDataAccessOperation(Account account) {}
@Before("accountDataAccessOperation(account)")
public void validateAccount(Account account) {
// ...
}
5.Advice Order 通知的顺序
可以使用@Order()对切面设定优先级
同一个切点有两个通知时(不在同一个切面中的两个通知):@Before 高优先级先运行 ,@After 高优先级后运行
在同一个切面重点两个通知,如果有运行顺序建议分两个切面