Spring AOP
- 定义注解
package com.ways.mount.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataScope {
String deptAlias() default "";
String userAlias() default "";
}
- 定义目标方法
package com.ways.mount.service;
import com.ways.mount.annotation.DataScope;
import com.ways.mount.controller.request.UserRequest;
import com.ways.mount.controller.response.UserVO;
import org.springframework.stereotype.Service;
@Service
public class TestService {
@DataScope(userAlias = "1111", deptAlias = "2222")
public UserVO getUser(UserRequest request, Integer age) {
try {
int i = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("测试一下");
}
return new UserVO("张三",request.getSalary());
}
}
- 定义切面
package com.ways.mount.aspect;
import com.ways.mount.annotation.DataScope;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
@Slf4j
public class DataScopeAspect {
@Before("@annotation(dataScope)")
public void doBefore(JoinPoint point, DataScope dataScope) {
log.error("执行了doBefore");
}
@After("@annotation(dataScope)")
public void doAfter(JoinPoint point, DataScope dataScope) {
log.error("执行了doAfter");
}
@AfterReturning(value = "@annotation(dataScope)",returning = "result")
public void doAfterReturning(JoinPoint point, DataScope dataScope, Object result) {
log.error("doAfterReturning");
}
@AfterThrowing(value = "@annotation(dataScope)", throwing = "exception")
public void doAfterThrowing(JoinPoint point, DataScope dataScope, Exception exception) {
log.error("doAfterThrowing");
}
@Around("@annotation(dataScope)")
public Object doAround(ProceedingJoinPoint pjp, DataScope dataScope) {
String methodName = pjp.getSignature().getName();
log.error("==========环绕通知开始了==========");
Object result = null;
try{
log.error("【目标方法】"+methodName);
result = pjp.proceed();
log.error("目标方法返回结果为:"+result);
}catch (Throwable e) {
log.error(e.getMessage());
}
log.error("后置通知执行");
return result;
}
}