项目中第一次用到自定义注解,这里简单记一下,以方便以后忘了来回顾一下
自定义注解
/**
* 修改方法日志注解
*/
@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface EditLog {
String logDesc();
}
切面类
@Component
@Aspect
public class EditLogAspect {
@Autowired
private MongoTemplate mongoTemplate;
@Pointcut("@annotation(xx.xx.xx.EditLog)")//切入带有此注解的方法
public void controllerAspect() {
}
@Around(value = "controllerAspect()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("进入切面");
Object[] args = pjp.getArgs();//获取参数
System.out.println(args[0].toString());
//方法执行之前查一次数据库
Object o= pjp.proceed();
//方法执行后查一次数据库
JSONObject resultJson = (JSONObject) JSON.toJSON(o);
HttpStatus code = resultJson.getObject("code", HttpStatus.class);//自己封装了统一的返回对象,对象中包含状态码,在这里获取
if (code.is2xxSuccessful()) {
System.out.println("成功");
Signature sig = pjp.getSignature();
MethodSignature msig =(MethodSignature) sig;
Object target = pjp.getTarget();
Method method = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
//得到方法上此注解的信息
String logDesc = method.getAnnotation(EditLog.class).logDesc();
System.out.println(logDesc);
}
}