Spring aop handles service-layer logs and exceptions. spring aop
1. What is aop?
AOP is short for Aspect Oriented Programming. It is equivalent to object-oriented Programming in Object Oriented Programming.
From the perspective of OOP, we focus on the processing logic of the business, which is a vertical behavior. From the perspective of AOP, we focus on the problem of object behavior, which is a horizontal behavior.
2. Functions of AOP:
2.1 call of monitoring functions
2.2 capture exceptions
The actual application is transaction, security, log, and other cross-cutting concerns.
The following is an example of the method log of aop printing service layer: Each annotation is easy to understand, such as after execution before and after execution.
@ Component
@ Aspect
Public class ApiServiceAspect {
Private final Logger logger = Logger. getLogger (this. getClass ());
/**
* Cut surface
*/
Private final String POINT_CUT = "execution (* com. demo. service .*.*.*(..))";
@ Pointcut (POINT_CUT)
Private void pointcut (){}
@ Before (value = POINT_CUT)
Public void before (JoinPoint joinPoint ){
String className = joinPoint. getTarget (). getClass (). getName ();
String methodName = joinPoint. getSignature (). getName ();
StringBuilder log = new StringBuilder ();
Log. append ("before :")
. Append (className)
. Append ("@")
. Append (methodName)
. Append (", params :");
Object [] args = joinPoint. getArgs ();
For (Object arg: args ){
Log. append (JSONObject. toJSONString (arg) + ",");
}
Logger.info (log. toString ());
}
@ AfterReturning (value = "pointcut ()", returning = "returnObj ")
Public void afterReturn (Object returnObj ){
String result = JSONObject. toJSONString (returnObj );
Logger.info ("afterReturning:" + result );
}
@ AfterThrowing (value = POINT_CUT, throwing = "e ")
Public void afterThrowing (Throwable e ){
Logger. error ("afterThrowing:" + e. getMessage (), e );
}
@ Around (value = "pointcut ()")
Public Object around und (ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Long begin = System. currentTimeMillis ();
StringBuilder log = new StringBuilder ("around :");
Object result = null;
Try {
Result = proceedingJoinPoint. proceed ();
} Catch (Exception e ){
Logger. error (log + e. getMessage (), e );
}
Long end = System. currentTimeMillis ();
Log. append ("execution time :")
. Append (end-begin)
. Append ("ms ");
Return result;
}
}
3. Configuration File
<Context: component-scan base-package = "com. jjshome. bigdata"/>
<Aop: aspectj-autoproxy> </aop: aspectj-autoproxy>
If spring mvc is used, put <aop: aspectj-autoproxy proxy-target-class = "true"/> in application. aop may be invalid in the xml file, and it is better to put it in the dispatcher-servlet.xml File