Use AOP + Annotation to implement Operation logging, aopannotation
Create annotation OperInfo first
1 @ Target ({ElementType. TYPE, ElementType. METHOD}) 2 @ Retention (RetentionPolicy. RUNTIME) 3 @ Documented4 @ Inherited5 public @ interface OperInfo {6 7 public String description () default ""; // operation description 8 9}
Create a face-cutting LogAspect for AOP.
Public class LogAspect {@ Resourceprivate OperationLogService operService; public Object doAroundMethodForCtLog (ProceedingJoinPoint pjp) throws Throwable {Method method = getMethod (pjp); if (method! = Null & method. isAnnotationPresent (OperInfo. class) {OperInfo annotation = method. getAnnotation (OperInfo. class); String descpTemp = annotation. description (); String description = executeTemplate (descpTemp, pjp); HttpServletRequest request = HttpServletUtils. getRequest (); Users user = (Users) request. getSession (). getAttribute ("users"); OperationLog operation = new OperationLog (); operation. setChangetime (new Date (); operation. setChangeuserid (user. getUsersid (); operation. setOptid (UUIDUtils. getUUID (); operation. setDescription ("user:" + user. getUsername () + ", log information: [{" + description + "}]"); operService. insertService (operation);} return pjp. proceed ();} // parse SPELprivate String executeTemplate (String template, ProceedingJoinPoint joinPoint ){
LocalVariableTableParameterNameDiscoverer parameterNameDiscovere = new LocalVariableTableParameterNameDiscoverer (); Method method = getMethod (joinPoint); String [] parameterNames = parameterNameDiscovere. getParameterNames (method); EvaluationContext context = new StandardEvaluationContext (); ExpressionParser parser = new SpelExpressionParser (); Object [] args = joinPoint. getArgs (); if (args. length = parameterNames. length) {for (int I = 0, len = args. length; I <len; I ++) {context. setVariable (parameterNames [I], args [I]) ;}} return parser. parseExpression (template, new TemplateParserContext ()). getValue (context, String. class);} private Method getMethod (ProceedingJoinPoint joinPoint) {Object target = joinPoint. getTarget (); Method method = (MethodSignature) joinPoint. getSignature ()). getMethod (); try {method = target. getClass (). getMethod (method. getName (), method. getParameterTypes ();} catch (Exception e) {e. printStackTrace ();} return method ;}}
Spring-mvc.xml Configuration
<bean class="com.aop.LogAspect" id="logAspect" /><aop:config expose-proxy="true"><aop:pointcut expression="execution(* com.service.impl.*Impl.*(..))" id="txPointcut"/><aop:aspect ref="logAspect" ><aop:around method="doAroundMethodForCtLog" pointcut-ref="txPointcut" /></aop:aspect></aop:config>
Add annotations to the service to be intercepted.
@ OperInfo (description = "added a user named # {# user. username}") public int insertUser (Users user ){}