什么是AOP?
AOP面向切面,切面将那些与业务无关,却被业务模块共同调用的逻辑提取并封装起来,减少了系统中的重复代码,降低了模块间的耦合度,同时提高了系统的可维护性。
实现策略JAVA SE动态代理
CGLib
相关注解
@Aspect(方面)
@Pointcut(切入点)
@Before(之前)
@After(之后)
pom.xml
<!--引用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()); } }
原文地址:https://www.cnblogs.com/dzcici/p/10472806.html
时间: 2024-11-05 22:40:19