In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is about Spring AOP how to achieve a simple log section, the editor feels very practical, so share with you to learn, I hope you can learn something after reading this article, say no more, follow the editor to have a look.
AOP1. What is AOP?
The full name of AOP is Aspect Oriented Programming, which is translated as aspect-oriented programming. it is a technology to realize the unified maintenance of crosscutting behavior outside the core business logic through precompilation and runtime dynamic proxy. AOP is a supplement and extension to object-oriented programming (OOP). AOP can be used to isolate all parts of business logic, so as to reduce the coupling between modules, and encapsulate the common behaviors that affect multiple classes into a reusable module, so as to improve the reusability of the program, improve the development efficiency, and improve the maneuverability and maintainability of the system.
two。 Why use AOP?
In the actual Web project development, we often need to implement logging, performance statistics, security control, transaction handling, exception handling and so on. If we write this code independently for each class at each level, the code will become difficult to maintain over time, so we separate these functions from the business logic code and aggregate them for maintenance. and we have the flexibility to choose where to use the code.
The core concept of 3.AOP, the noun concept understanding Notification (Advice), intercepts the code to be executed after the join point is intercepted. The notification is divided into five types of functions that we want to implement, such as logging, performance statistics, security control, transaction handling, exception handling, etc., and indicate when and what the connection point (Joint Point) is intercepted. Such as intercepted methods, access to class members and execution of exception handler blocks, etc., can also nest other places where Joint PointSpring allows you to use notifications, before and after the method before and after (including throwing exceptions) pointcut (Pointcut) intercept the definition of the join point (Pointcut) specifies which method to notify, and where to Aspect the definition of the facet class It contains the definition of Pointcut and Advice, that is, the object selected by the Target Object, that is, the object that needs to be notified. Because Spring AOP is implemented through the proxy pattern, the object is always the process of creating an AOP proxy object by weaving (Weaving) aspects to the target object by the business logic of the proxy object itself. Weaving can be done at compile time, class loading time, and run time, while Spring uses the completion pointcut at run time to define which join points will be notified (Introduction) can dynamically add methods and fields to the class at run time Spring allows the introduction of new interfaces to all target objects is to introduce new interface enhancements on the basis of an interface / class AOP proxy (AOP Proxy) Spring AOP can use JDK dynamic proxy or CGLIB proxy, the former is based on interface, the latter applies faceted Spring AOP1 to target objects through proxies based on classes. Brief introduction
AOP is a core content of Spring framework. In Spring, the AOP agent can be implemented using either the JDK dynamic agent or the CGLIB agent CglibAopProxy. The IOC container of AOP substitute Spring in Spring is responsible for generation and management, and its dependencies are also managed by the IOC container.
two。 Related annotations indicate that @ Aspect defines a java class as an aspect class @ Pointcut defines a pointcut, which can be a regular expression, such as all functions under a package in the following example, or an annotation, etc. @ Before cuts content at the beginning of the pointcut @ After at the end of the pointcut @ AfterReturning after the pointcut return content processing logic @ Around before and after the pointcut And control when the content of the pointcut itself @ AfterThrowing is used to handle the processing logic @ Order (100) AOP section execution order when an exception is thrown in the content section. The smaller the @ Before value, the first the execution. The higher the @ After and @ AfterReturning values, the more they execute first, where @ Before, @ After, @ AfterReturning, @ Around, and @ AfterThrowing all belong to Advice.
Using AOP to achieve Web log processing 1. Build Project 2. Add dependency org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test Org.springframework.boot spring-boot-devtools true org.springframework.boot spring-boot-starter-aop 3.Web log notes @ Documented@Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.METHOD) public @ interface ControllerWebLog {String name () / / the name of the called interface boolean intoDb () default false;// identifies whether the operation log needs persistent storage} 4. Implement aspect logic @ Aspect@Component@Order (100) public class WebLogAspect {private static final Logger logger = LoggerFactory.getLogger (WebLogAspect.class); private ThreadLocal threadLocal = new ThreadLocal (); / * * crosscut point * / @ Pointcut ("execution (public * cn.zwqh.springboot.controller..*.* (..)") Public void webLog () {} / * receive request And record the data * @ param joinPoint * @ param controllerWebLog * / @ Before (value = "webLog () & & @ annotation (controllerWebLog)") public void doBefore (JoinPoint joinPoint, ControllerWebLog controllerWebLog) {/ / received the request RequestAttributes ra = RequestContextHolder.getRequestAttributes () ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest (); / / record the request content. ThreadInfo stores all content Map threadInfo = new HashMap (); logger.info ("URL:" + request.getRequestURL ()); threadInfo.put ("url", request.getRequestURL ()) Logger.info ("URI:" + request.getRequestURI ()); threadInfo.put ("uri", request.getRequestURI ()); logger.info ("HTTP_METHOD:" + request.getMethod ()); threadInfo.put ("httpMethod", request.getMethod ()); logger.info ("REMOTE_ADDR:" + request.getRemoteAddr ()) ThreadInfo.put ("ip", request.getRemoteAddr ()); logger.info ("CLASS_METHOD:" + joinPoint.getSignature () .getDeclaringTypeName () + "." + joinPoint.getSignature () .getName ()) ThreadInfo.put ("classMethod", joinPoint.getSignature (). GetDeclaringTypeName () + "." + joinPoint.getSignature (). GetName ()); logger.info ("ARGS:" + Arrays.toString (joinPoint.getArgs (); threadInfo.put ("args", Arrays.toString (joinPoint.getArgs () Logger.info ("USER_AGENT" + request.getHeader ("User-Agent")); threadInfo.put ("userAgent", request.getHeader ("User-Agent")); logger.info ("execution method:" + controllerWebLog.name ()); threadInfo.put ("methodName", controllerWebLog.name ()); threadLocal.set (threadInfo) } / * successful post-processing * @ param controllerWebLog * @ param ret * @ throws Throwable * / @ AfterReturning (value = "webLog () & & @ annotation (controllerWebLog)", returning = "ret") public void doAfterReturning (ControllerWebLog controllerWebLog, Object ret) throws Throwable {Map threadInfo = threadLocal.get () ThreadInfo.put ("result", ret); if (controllerWebLog.intoDb ()) {/ / insert database operation / / insertResult (threadInfo);} / / return content logger.info ("RESPONSE:" + ret) after processing the request } / * get execution time * @ param proceedingJoinPoint * @ return * @ throws Throwable * / @ Around (value = "webLog ()") public Object doAround (ProceedingJoinPoint proceedingJoinPoint) throws Throwable {long startTime = System.currentTimeMillis (); Object ob = proceedingJoinPoint.proceed () Map threadInfo = threadLocal.get (); Long takeTime = System.currentTimeMillis ()-startTime; threadInfo.put ("takeTime", takeTime); logger.info ("time-consuming:" + takeTime); threadLocal.set (threadInfo); return ob } / * * exception handling * @ param throwable * / @ AfterThrowing (value = "webLog ()", throwing = "throwable") public void doAfterThrowing (Throwable throwable) {RequestAttributes ra = RequestContextHolder.getRequestAttributes (); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest () / / exception information logger.error ("{} API call exception, exception information {}", request.getRequestURI (), throwable);}} 5. The test interface @ RestController@RequestMapping ("/ user") public class UserController {@ GetMapping ("/ getOne") @ ControllerWebLog (name = "query", intoDb = true) public String getOne (Long id, String name) {return "1234";}} 6. Run the test
Browser request: http://127.0.0.1:8080/user/getOne?id=1&name=zwqh. You can see the output of the backend log:
Logging is just a simple example, and the application of Spring AOP makes the whole system more organized, and it is also very powerful in other scenarios. It helps us to reduce the coupling between modules, improve program reusability, improve development efficiency, and improve system workability and maintainability.
This is how Spring AOP implements simple log sections, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.