假如咱們須要作一個功能——受權訪問,即對全部的方法的訪問以前須要判斷用戶是否登錄,只有登錄的用戶才能夠訪問方法。對於這個情景,若是選擇在每個方法內加上用戶登陸判斷,那麼就會形成大量的代碼冗餘,由此引出AOP的使用。java
使用AOP(面向切面編程),咱們能夠把判斷用戶是否登錄做爲一個切面,插入到每個方法執行的各個位置。web
這裏,咱們以記錄請求日誌爲例子,記錄下SpringBoot中AOP的使用:spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>1.5.6.RELEASE</version> </dependency>
(chrome中右鍵選「在新標籤中打開圖片」便可查看大圖)chrome
源碼以下:編程
package com.example.demo.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; @Aspect @Component public class HttpAspect { private static final Logger logger= LoggerFactory.getLogger(HttpAspect.class); @Pointcut("execution(public * com.example.demo.controller.StudentController.*(..))") public void log(){} @Before("log()") public void doBefore(JoinPoint joinPoint){ //url ServletRequestAttributes attributes= (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request=attributes.getRequest(); logger.info("url={}",request.getRequestURL()); //method logger.info("method={}",request.getMethod()); //ip logger.info("ip={}",request.getRemoteAddr()); //類方法 logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+ "." +joinPoint.getSignature().getName()); //參數 logger.info("args={}", joinPoint.getArgs()); } @After("log()") public void doAfter(){ logger.info("2222222222222"); } @AfterReturning(returning = "object",pointcut = "log()") public void doAfterReturning(Object object){ logger.info("response={}",object); } }