In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "Spring AOP how to achieve complex logging operations", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "Spring AOP how to achieve complex logging operations" this article.
Spring AOP complex logging (custom comments)
In doing the project, the business logic requires that all changes to the database data need to be logged (add, delete, modify). The contents recorded include the operator, the table name and table name of the operation, the specific operation, and the data corresponding to the operation.
The first thing that comes to mind is the AOP feature of Spring. However, after some understanding, it is found that general logging can only record some simple operations, such as table name, table name and so on.
So think of the method of custom annotation, put the content you want to record in the annotation, through the entry point to get the annotation parameters, you can get the data you want, record in the database. Follow this train of thought, look up some relevant information on the Internet, and finally realize the function. Needless to say, here are the ideas and code for the implementation:
The first step
Add custom comments to the code and define two properties, one is the log description (description), and the other is the operation table type (tableType). The attribute parameters can be changed as needed. The code is as follows:
Import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target / * ClassName: SystemServiceLog * Function: AOP logging, Custom Note * date: 9:29:01 * @ author lcma * @ version * @ since JDK 1.7 * / @ Target ({ElementType.PARAMETER, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documented public @ interface SystemServiceLog {/ * Log description * / String description () default "" / * * Operation table type * / int tableType () default 0;} step 2
Define the aspect class, obtain the aspect parameters, and save the database as follows:
Import java.lang.reflect.Method;import java.util.Date; import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes; import com.iflytek.zhbs.common.annotation.SystemServiceLog Import com.iflytek.zhbs.common.util.JacksonUtil;import com.iflytek.zhbs.common.util.WebUtils;import com.iflytek.zhbs.dao.BaseDaoI;import com.iflytek.zhbs.domain.CmsAdmin;import com.iflytek.zhbs.domain.CmsOperationLog; @ Aspect@Component@SuppressWarnings ("rawtypes") public class SystemLogAspect {@ Resourceprivate BaseDaoI logDao; / * logging * / private static final Logger LOGGER = Logger.getLogger (SystemLogAspect.class) / * Service layer pointcut * / @ Pointcut ("@ annotation (com.iflytek.zhbs.common.annotation.SystemServiceLog)") public void serviceAspect () {} / * doServiceLog: get the annotation parameters and log. * @ author lcma * @ param joinPoint pointcut parameter * @ since JDK 1.7 * / @ After ("serviceAspect ()") public void doServiceLog (JoinPoint joinPoint) {LOGGER.info ("logging"); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes ()). GetRequest (); / / get administrator user information CmsAdmin admin = WebUtils.getAdminInfo (request) Try {/ / Database log CmsOperationLog log = new CmsOperationLog (); log.setOperationType (getServiceMthodTableType (joinPoint)); / / get log description information String content = getServiceMthodDescription (joinPoint); log.setContent (admin.getRealName () + content); log.setRemarks (getServiceMthodParams (joinPoint)); log.setAdmin (admin) Log.setCreateTime (new Date ()); logDao.save (log);} catch (Exception e) {LOGGER.error ("exception information: {}", e);}} / * getServiceMthodDescription: get the description information of the method in the annotation for the service layer annotation. * @ author lcma * @ param joinPoint pointcut * @ return method description * @ throws Exception * @ since JDK 1.7 * / private String getServiceMthodDescription (JoinPoint joinPoint) throws Exception {String targetName = joinPoint.getTarget () .getClass () .getName (); String methodName = joinPoint.getSignature () .getName (); Object [] arguments = joinPoint.getArgs () Class targetClass = Class.forName (targetName); Method [] methods = targetClass.getMethods (); String description = ""; for (Method method: methods) {if (method.getName (). Equals (methodName)) {Class [] clazzs = method.getParameterTypes () If (clazzs.length = = arguments.length) {description = method.getAnnotation (SystemServiceLog.class). Description (); break;} return description;} / * getServiceMthodTableType: get the data table type of the method in the annotation for the service layer annotation. * @ author lcma * @ param joinPoint * @ return * @ throws Exception * @ since JDK 1.7 * / private nt getServiceMthodTableType (JoinPoint joinPoint) throws Exception {String targetName = joinPoint.getTarget () .getClass () .getName (); String methodName = joinPoint.getSignature () .getName (); Object [] arguments = joinPoint.getArgs (); Class targetClass = Class.forName (targetName) Method [] methods = targetClass.getMethods (); int tableType = 0; for (Method method: methods) {if (method.getName (). Equals (methodName)) {Class [] clazzs = method.getParameterTypes (); if (clazzs.length = = arguments.length) {tableType = method.getAnnotation (SystemServiceLog.class). TableType (); break } return tableType;} / * getServiceMthodParams: get the parameters in json format. * @ author lcma * @ param joinPoint * @ return * @ throws Exception * @ since JDK 1.7 * / private String getServiceMthodParams (JoinPoint joinPoint) throws Exception {Object [] arguments = joinPoint.getArgs (); String params = JacksonUtil.toJSon (arguments); return params;}}
It should be noted that when defining pointcuts, @ Pointcut contains the path of custom annotations.
The data transmitted by each section is different, and it is finally decided that all the parameters of the section will be obtained, converted into json strings, and saved to the database.
Step three
Make comments where the log needs to be recorded in service, as follows:
@ SystemServiceLog (description=Constants.ADMIN_SAVE_OPTIONS,tableType=Constants.ADMIM_TABLE_TYPE)
Code picture:
Configure the parameter content of the custom annotation in the constant class:
The fourth step
Add the package path where the aspect class resides to the automatic scanning path of Spring annotations, and start the support for @ AspectJ annotations as follows:
Finally, the effect of recording data in the database is shown in the figure:
OK, the function has been realized, write a blog for the first time, write a bad place, please forgive me.
Multiple annotations can be merged into one, including custom annotations
In spring, sometimes a class is marked with a lot of comments.
In fact, Java annotations can be inherited (that is, multiple annotations are merged into one)
For example, SpringMVC's comment @ RestController@RequestMapping ("/ person")
Can be merged into one
@ PathRestController ("/ user")
The implementation is:
Import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.core.annotation.AliasFor;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Documented@RestController@RequestMappingpublic @ interface PathRestController {@ AliasFor ("path") String [] value () default {} @ AliasFor ("value") String [] path () default {};} above is all the content of the article "how Spring AOP implements complex logging operations". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to 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.