We have the need to record the user operation of a method of information and recorded in the log, for example, when the user saves and updates the task, we need to record the user's IP, whether to save or update, which method is called, save and update the task name and the operation is successful.
The best technique here is Spring AOP + annotation, and first I'll define an annotation class
/** * parameter name well, I'll take it easy, just to demonstrate the usage * @author liuxg * @date April 13, 2016 morning 7:53:52 */ @Documented @Retention (retentionpolicy.runtime) @Target (elementtype.method) public @interface logger {String param1 () default default ""; String param3 () default ""; String param4 () default
Then we define a method in the controller that is a method of saving or updating a user-specific invocation.
@RequestMapping("/mvc24")@Logger(param1 = "#{task.project.projectName}",param2 = "#{task.taskName}",param3 = "#{name}",param4 = "常量")public void mvc24(Task task ,String name){ //...}
Here we can bind the information about the task or name in the parameter to the annotation class.
Then we define a slice, and we can dynamically get and process some information about the annotation class.
/** * Log slices *@author LIUXG *@date October 13, 2015 5:55:44 * *@Component@AspectPublicclass loggeraspect { @Around (" @annotation (Com.liuxg.logger.annotation.Logger) ") public Object around (Joinpoint joinpoint) {methodsignature Methodsignature = (methodsignature) joinpoint.getsignature (); Method method = Methodsignature.getmethod (); Logger Logger = (Logger) method.getannotation (Logger.class); Object value1 = annotationresolver.newinstance (). Resolver (Joinpoint, logger.param1 ()); Object value2 = annotationresolver.newinstance (). Resolver (Joinpoint, logger.param1 ()); Object value3 = annotationresolver.newinstance (). Resolver (Joinpoint, logger.param1 ()); Object value4 = annotationresolver.newinstance (). Resolver (Joinpoint, logger.param1 ()); return null;}
Annotationresolver is a parser that I wrote on this side of the parsing annotation class syntax, which can be used to parse the syntax of the annotation class directly into the #{method variable name}
The parser has only one method
/** * 解析注解上的值 * @param joinPoint 切面类,直接在aop里面获取,参考上面的例子 * @param str 需要解析的字符串 * @return */public Object resolver(JoinPoint joinPoint, String str)
Download from this address
Https://github.com/liuxg2013/AnnotationResolver.git
Java solutions for binding method parameters in annotations