在SpringBoot中配置controller層切面和service層切面的區別
阿新 • • 發佈:2019-02-20
其實區別很簡單,貼兩端程式碼一目瞭然
service層的aop
package com.yy.aop; //省略匯入包 @Aspect @Service("logAspect") public class LogAspect { @Pointcut("execution(* com.newer.service.*.*(..))") public void anyMethod(){ } @Before("anyMethod()") public void before(JoinPoint joinPoint){ String name=joinPoint.getSignature().getName(); System.out.println(name+"方法的前置通知"); } @AfterReturning("anyMethod()") public void afterMethod(){ System.out.println("後置通知!"); } @AfterThrowing("anyMethod()") public void afterThrowing()throws Throwable{ System.out.println("異常通知"); } @After("anyMethod()") public void finalMethod(){ System.out.println("最終通知"); } @Around("anyMethod()") public Object aroundMethod(ProceedingJoinPoint pjp)throws Throwable{ System.out.println("環繞通知"); return pjp.proceed(); } }
接下來看controller層的切面
package com.yy.springbootdemo.hospital.controller; @Aspect @Component //每個切面最終還是要掃面到斌容器裡面去,成為bin容器的元件 @Order(4) public class WebLogAspect { //獲取日誌記錄器 private Logger logger=Logger.getLogger(getClass()); //獲取執行緒副本 ThreadLocal<Long> startTime=new ThreadLocal<>(); @Pointcut("execution(public * com.*.*.*.controller.*.*(..))") public void weblog(){} @Before("weblog()") public void doBefore(JoinPoint joinPoint){ //獲取請求報文頭部元資料 ServletRequestAttributes requestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); //獲取請求物件 HttpServletRequest request=requestAttributes.getRequest(); //記錄控制器執行前的時間毫秒數 startTime.set(System.currentTimeMillis()); logger.info("前置通知執行:"); logger.info("url:"+request.getRequestURL()); logger.info("method:"+request.getMethod()); logger.info("ip:"+request.getRemoteAddr()); logger.info("class_method:"+joinPoint.getSignature().getDeclaringTypeName()+ "."+joinPoint.getSignature().getName()); logger.info("args:"+ Arrays.toString(joinPoint.getArgs())); } @AfterReturning(returning = "ret",pointcut = "weblog()") public void doAfter(Object ret){ logger.info("後置通知執行:"); logger.info("RESPONSE:"+ret); logger.info("spend:"+(System.currentTimeMillis()-startTime.get())); } }