什麼是AOP?web
AOP面向切面,切面將那些與業務無關,卻被業務模塊共同調用的邏輯提取並封裝起來,減小了系統中的重複代碼,下降了模塊間的耦合度,同時提升了系統的可維護性。spring
實現策略JAVA SE動態代理app
CGLibspring-boot
相關注解spa
@Aspect(方面)代理
@Pointcut(切入點)日誌
@Before(以前)code
@After(以後)orm
pom.xmlxml
<!--引用AOP--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
AspectTest.class
/** * @author 張東明 * @TODO: 2019/3/4 * @remark AOP切面類 日誌記錄 */ @Aspect @Component public class AspectTest { private final static Logger logger = LoggerFactory.getLogger(AspectTest.class); @Autowired private GeLogVisitServiceImpl geLogVisitService; @Pointcut("execution(public * com.nf147.platform.web..*.*(..))") public void controllerMethod() { } @Before("controllerMethod()") public void LogRequestInfo(JoinPoint joinPoint) throws JsonProcessingException { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); /** * 獲取Session * */ GeEnterprise user = (GeEnterprise) request.getSession().getAttribute("user"); int id = 0; if (user != null) { id = user.getId(); } String remoteAddr = request.getRemoteAddr(); String requestURI = request.getRequestURI(); if (remoteAddr != null && requestURI != null) { GeLogVisit geLogVisit = null; if (id > 0) { geLogVisit = new GeLogVisit(id, remoteAddr, requestURI, new Date(), 1); } else { geLogVisit = new GeLogVisit(remoteAddr, requestURI, new Date(), 1); } System.out.println("日誌記錄信息:" + geLogVisit.toString()); int insert = geLogVisitService.insert(geLogVisit); System.out.println(insert); } StringBuffer requestLog = new StringBuffer(); requestLog.append("請求信息:") .append("URL = {" + requestURI + "},\t") .append("HTTP_METHOD = {" + request.getMethod() + "},\t") .append("IP = {" + remoteAddr + "},\t") .append("CLASS_METHOD = {" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + "},\t"); if (joinPoint.getArgs().length == 0) { requestLog.append("ARGS = {} "); } else { requestLog.append("ARGS = " + new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL) .writeValueAsString(joinPoint.getArgs()[0]) + ""); } System.out.println(requestLog.toString()); } /** * @remark 調用以後迴歸返回結果 * // TODO: 2019/3/4 */ @AfterReturning(returning = "resultVO", pointcut = "controllerMethod()") public void logResultVOInfo(JSONResponse resultVO) throws Exception { System.out.println("請求結果:" + resultVO.getCode() + "\t" + resultVO.getData()); } }