区别:@Before(前置通知Before advice)是在所拦截方法执行之前执行一段逻辑。
@After 后通知(After advice是在所拦截方法执行之后执行一段逻辑。
@Around 环绕通知(Around advice) 是可以同时在所拦截方法的前后执行一段逻辑,用这个注解的方法入参传的是ProceedingJionPoint pjp,可以决定当前线程能否进入核心方法中——通过调用pjp.proceed();
demo:
下面可将 @Around(“loggerPointCut()”)改为@Before(“loggerPointCut()”)或@After(“loggerPointCut()”)
在需要通知的方法上加上@SysLogger(“rocketmq测试咯”)
controller里:
@GetMapping("/produce")
@SysLogger(“rocketmq测试咯”)
public MelotResult produce(@RequestParam(name=“topic”)String topic,
@RequestParam(“tag”)String tag,
@RequestParam(“keys”)String keys,
@RequestParam(“msg”)String msg
){
log.info(“topic=={},tag=={},keys=={},msg=={},delayTime=={}”,topic,tag,keys,msg);
boolean sent = producerService.sent(topic, tag, keys, msg, null);
return new MelotResult(sent);
}
通知方法:
SysLogger.java:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLogger {
String value() default “”;
}
SysLoggerFilter.java
@Component
@Aspect
public class SysLoggerFilter {
private static Logger log = LoggerFactory.getLogger(SysLoggerFilter.class);
@Pointcut("@annotation(com.forezp.annotation.SysLogger)")
public void loggerPointCut() {
}
@Around("loggerPointCut()")
public Object saveSysLog(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String loginUserId = request.getHeader("loginUserId");
MelotResult<Object> rs = new MelotResult<>();
if(StringUtils.isBlank(loginUserId)){
rs.setSuccess(false);
rs.setMsg("还没登录系统");
return rs;
}
return joinPoint.proceed();
}