spring Aop 中 Advice,PointCut, Advisor和Advised关系
- Advice: 增强, 如BeforeAdvice, AfterAdvice...
- Advisor表示增强定义,由 Advice和PointCut组成
- Advised 管理 Advisor
使用 spring Aop 定义增强
使用 spring Aop 定义增强,而不是用 AspectJ
java
@Slf4j
public class LogAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
log.info("before method: {}", method.getName());
}
}
@Configuration
public class SpringAopConfig {
@Bean
public LogAdvice logAdvice() {
return new LogAdvice();
}
@Bean
public Advisor logAdvisor() {
NameMatchMethodPointcut nameMatchMethodPointcut = new NameMatchMethodPointcut();
nameMatchMethodPointcut.addMethodName("ping");
return new DefaultPointcutAdvisor(nameMatchMethodPointcut, logAdvice());
}
}
结果:
bash
INFO 104836 --- [nio-8080-exec-3] com.proxy.sample.LogAdvice : before method: ping
使用 AspectJ 实现AOP
java
@Component
@Aspect
@Slf4j
public class LogAspect {
@Pointcut("execution(* com.controller.HealthController.*(..))")
public void pc() {
}
@Before("pc()")
public void log(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
log.info("before method: {}", signature.getName());
}
}
结果:
bash
INFO 96524 --- [nio-8080-exec-1] com.proxy.sample.LogAspect : before method: ping
AspectJ 和 Spring Aop区别
- 都可以实现AOP 增强
- AspectJ是在编译期
- Spring Aop则是运行时,动态创建,性能要稍微差点
- AspectJ 使用范围更广,不依赖spring, 而spring Aop则与spring 绑定