Aop常用注解
@Aspect:作用是把当前类标识为一个切面供容器读取
@Pointcut:Pointcut是植入Advice的触发条件。每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。
@Around:环绕增强
@AfterReturning:后置增强
@Before:标识一个前置增强方法
@AfterThrowing:异常抛出增强
@After: final增强,不管是抛出异常或者正常退出都会执行
1. 新建注解类AopFilter和AopFilters
@Retention(RUNTIME)
public @interface AopFilter {
String name();
String project();
}
2. 建注解类AopFilters
@Retention(RUNTIME)
public @interface AopFilters {
AopFilter[] value();
}
3. 某操作类
@Slf4j
@RestController
@RequestMapping(value = "/api")
public class AopController {
@RequestMapping(value= "/t1")
@ResponseBody
@AopFilters(value = {@AopFilter(name = Constant.NAME, project = Constant.PROJECT)})
public Map<String, Object> register(String name, Integer age, String address, Integer sex) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String sexName = "";
switch (sex) {
case 1:
sexName = "男";
break;
case 2:
sexName = "女";
break;
default:
break;
}
String birthday = "2008-08-08 00:00:00";
map.put("name", name);
map.put("age", age);
map.put("address", address);
map.put("sex", sexName);
map.put("birthday", birthday);
return map;
}
}
4. 切面类
@Component
@Aspect
public class Aop {
/***
* @deprecated: execution 匹配com.shy.springboot.controller包下所有类的所有方法的执行作为切入点
* returning 此处将res的类型声明为Object,意味着对目标方法的返回值不加限制
* ProceedingJoinPoint pjp : ProceedingJoinPoint is only supported for around advice
*/
@AfterReturning(value = "execution(* com.shy.springboot.controller.*.*(..)) && args(a,b,c,d)", returning = "res")
public void afterReturning(JoinPoint jp, Object res, String a, Integer b, String c, Integer d) {
Object[] args = jp.getArgs();
for (Object obj : args) {
System.out.println(obj);
}
Method sourceMethod = getSourceMethod(jp);
System.out.println(sourceMethod.getName());
System.out.println("方法参数:a,b,c,d :" + a + ", " + b + ", " + c + ", " + d);
System.out.println(res);
MethodSignature methodSignature = (MethodSignature) jp.getSignature();
//MethodSignature methodSignature = (MethodSignature) jp.getSignature();
Method proxyMethod = methodSignature.getMethod();
AopFilters annotation = proxyMethod.getAnnotation(AopFilters.class);
if(annotation != null) {
AopFilter[] value = annotation.value();
for (AopFilter aop : value) {
String project = aop.project();
String name = aop.name();
System.out.println("project :" + project);
System.out.println("name :" + name);
}
}
//HttpServletRequest request = WebContext.getInstance().getRequest();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Integer userId = (Integer) request.getAttribute("user_id");
String token = (String) request.getAttribute("token");
System.out.println("当前用户信息 user_id = " + userId + ", token = " + token );
}
}