SpringMVC custom annotation, using AOP to implement the logging method, springmvcaop

Source: Internet
Author: User

SpringMVC custom annotation, using AOP to implement the logging method, springmvcaop

Background

In a recent project, when the project is basically completed, the customer proposes to record all business operation logs to the database and extract some key business information (such as the transaction order number) it is reflected in logs.

In order to ensure the duration, after reviewing the materials, we decided to use the AOP + custom annotation method to complete this requirement.

Preparations

The jar package that the custom annotation needs to depend on has a aspectjrt-XXX.jar, A aspectjweaver-XXX.jar, and XXX stands for the version number.

Custom Annotation

A separate log package is created under the project to store log-related content.

**. Common. log. annotation // storage location of custom annotations **. common. log. aop // storage location of the aop tool class

Create a custom annotation class under the annotation package:

Package **. common. log. annotation; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target; @ Target ({ElementType. METHOD}) @ Retention (RetentionPolicy. RUNTIME) public @ interface XXXOperateLog {/*** operation type description * @ return */String operateTypeDesc () default ""; /*** operation type ** @ return */long operateType () default-1;/*** module code ** @ return */String moudleCode () default "M30 "; /*** Module name ** @ return */String moudleName () default "XX module";/*** business type ** @ return */String bussType () default ""; /*** business type description ** @ return */String bussTypeDesc () default "";}

Create XXXOperateLogAop under the aop package

Package **. common. log. aop; import **; // omit @ Aspect @ Componentpublic class XXXOperateLogAop {@ Autowired SystemLogService systemLogService; HttpServletRequest request = null; Logger logger = LoggerFactory. getLogger (XXXOperateLogAop. class); ThreadLocal <Long> time = new ThreadLocal <Long> (); // the unique identifier used to generate operation logs, call public static ThreadLocal for business process audit logs <String> tag = new ThreadLocal <String> (); // declare the AOP entry point. If XXXO is used PerateLog methods are intercepted @ Pointcut ("@ annotation (**. common. log. annotation. XXXOperateLog) ") public void log () {System. out. println ("I Am a starting point");}/*** click * @ param joinPoint */@ Before ("Log ()") in all annotation @ log fields ()") public void beforeExec (JoinPoint joinPoint) {time. set (System. currentTimeMillis (); info (joinPoint); // set the unique ID tag of the log. set (UUID. randomUUID (). toString (); request = (ServletRequestAttributes) RequestContex THolder. getRequestAttributes ()). getRequest () ;}@ After ("log ()") public void afterExec (JoinPoint joinPoint) {MethodSignature MS = (MethodSignature) joinPoint. getSignature (); Method method = ms. getMethod (); logger. debug ("marked as" + tag. get () + "method" + method. getName () + "Running consumption" + (System. currentTimeMillis ()-time. get () + "ms");} // This method will be executed during the execution of the target method. Here you can implement the log record @ Around ("log () ") public Object around und Exec (ProceedingJoinPoint pjp) throws Throwable {Object ret = pjp. proceed (); try {Object [] orgs = pjp. getArgs (); SystemLog valueReturn = null; for (int I = 0; I <orgs. length; I ++) {if (orgs [I] instanceof SystemLog) {valueReturn = (SystemLog) orgs [I] ;}} if (valueReturn = null) {valueReturn = new SystemLog ();} if (valueReturn! = Null & request! = Null) {MethodSignature MS = (MethodSignature) pjp. getSignature (); Method method = ms. getMethod (); // obtain the operation log information of the annotation XXXOperateLog log = method. getAnnotation (XXXOperateLog. class); String businessType = log. bussType (); String businessDesc = log. bussTypeDesc (); HashMap requestMap = ServletUtils. getParametersToHashMap (request); // find the business type from the parameter if (businessType. equals ("") {Object objBusinessType = requestMa P. get ("business_type"); businessType = objBusinessType = null? "": ObjBusinessType. toString () ;}// find the business type Object apply = request. getAttribute ("apply") from the Application Form of the execution result; if (apply! = Null) {JSONObject obj = JSONFactory. tojson?actentity (apply); if (obj! = Null) {valueReturn. setOtherDesc ("Application No.:" + obj. getString ("apply_no"); if (businessType. equals ("") {businessType = obj. getString ("business_type") ;}}// find the business type from the execution process parameters of the method (usually set manually) if (businessType. equals ("") {businessType = (String) request. getAttribute ("business_type"); businessType = null? "": BusinessType;} if (! BusinessType. equals ("") & businessDesc. equals ("") {businessDesc = XXXSysConstant. BUSINESS_TYPE.getName (businessType);} valueReturn. setBussType (XXXSysConstant. BUSINESS_TYPE.getNumber (businessType); valueReturn. setBussTypeDesc (businessDesc); valueReturn. setMoudleCode (log. moudleCode (); valueReturn. setMoudleName (log. moudleName (); valueReturn. setOperateResult (XXXSysConstant. yesOrNo. YES); valueRet Urn. setOperateType (log. operateType (); valueReturn. setInputUserId (UserContext) WebUtils. getSessionAttribute (request, "XXXuserContext ")). getSysUser (). getId (); valueReturn. setOperateTypeDesc (log. operateTypeDesc (); valueReturn. setRequestIp (getRemoteHost (request); valueReturn. setRequestUrl (request. getRequestURI (); valueReturn. setServerIp (request. getLocalAddr (); valueReturn. setUids (tag. get ());// Save the operation log systemLogService. saveSystemLog (valueReturn);} else {logger.info ("do not record log information");} // save operation result} catch (Exception e) {e. printStackTrace ();} return ret;} // records the exception log @ AfterThrowing (pointcut = "log ()", throwing = "e") public void doAfterThrowing (JoinPoint joinPoint, throwable e) {try {info (joinPoint); Object [] orgs = joinPoint. getArgs (); SystemLog valueReturn = null; for (int I = 0; I <orgs. length; I ++) {If (orgs [I] instanceof SystemLog) {valueReturn = (SystemLog) orgs [I] ;}} if (valueReturn = null) {valueReturn = new SystemLog ();} if (valueReturn! = Null & request! = Null) {MethodSignature MS = (MethodSignature) joinPoint. getSignature (); Method method = ms. getMethod (); XXXOperateLog log = method. getAnnotation (XXXOperateLog. class); String businessType = log. bussType (); String businessDesc = log. bussTypeDesc (); if (businessType. equals ("") {Object objBusinessType = ServletUtils. getParametersToHashMap (request ). get ("business_type"); businessType = objBusinessType = Null? "": ObjBusinessType. toString (); businessDesc = XXXSysConstant. BUSINESS_TYPE.getName (businessType);} valueReturn. setBussType (XXXSysConstant. BUSINESS_TYPE.getNumber (businessType); valueReturn. setBussTypeDesc (businessDesc); valueReturn. setMoudleCode (log. moudleCode (); valueReturn. setMoudleName (log. moudleName (); valueReturn. setOperateType (log. operateType (); valueReturn. setOperateTypeDesc (log. bytes AteTypeDesc (); valueReturn. setInputUserId (UserContext) WebUtils. getSessionAttribute (request, "XXXuserContext ")). getSysUser (). getId (); valueReturn. setOperateResult (XXXSysConstant. yesOrNo. NO); String errMes = e. getMessage (); if (errMes! = Null & errMes. length () & gt; 800) {errMes = errMes. substring (0,800);} valueReturn. setErrorMessage (errMes); valueReturn. setRequestIp (getRemoteHost (request); valueReturn. setRequestUrl (request. getRequestURI (); valueReturn. setServerIp (request. getLocalAddr (); valueReturn. setUids (tag. get (); systemLogService. saveSystemLog (valueReturn);} else {logger.info ("do not record log information") ;}} catch (Exception e1) {e1.printSt AckTrace () ;}} private void info (JoinPoint joinPoint) {logger. debug ("--------------------------------------------------"); logger. debug ("King: \ t" + joinPoint. getKind (); logger. debug ("Target: \ t" + joinPoint. getTarget (). toString (); Object [] OS = joinPoint. getArgs (); logger. debug ("Args:"); for (int I = 0; I <OS. length; I ++) {logger. debug ("\ t => parameter [" + I + "]: \ t" + OS [I]. toString ();} logger. deb Ug ("Signature: \ t" + joinPoint. getSignature (); logger. debug ("SourceLocation: \ t" + joinPoint. getSourceLocation (); logger. debug ("StaticPart: \ t" + joinPoint. getStaticPart (); logger. debug ("------------------------------------------------");}/*** obtain the remote client Ip Address * @ param request * @ return */private String getRemoteHost (javax. servlet. http. httpServletRequest request) {String ip = request. getHeader ("x-f Orwarded-for "); if (ip = null | ip. length () = 0 | "unknown ". equalsIgnoreCase (ip) {ip = request. getHeader ("Proxy-Client-IP");} if (ip = null | ip. length () = 0 | "unknown ". equalsIgnoreCase (ip) {ip = request. getHeader ("WL-Proxy-Client-IP");} if (ip = null | ip. length () = 0 | "unknown ". equalsIgnoreCase (ip) {ip = request. getRemoteAddr ();} return ip. equals ("0: 0: 0: 0: 0: 0: 0: 1 ")? "127.0.0.1": ip ;}}

Modify the configuration file spring-mvc.xml and add the following configuration

<! -- Enable AOP interception --> <aop: aspectj-autoproxy proxy-target-class = "true"/> <mvc: annotation-driven/> <! -- Define the scope of Spring description Bean --> <context: component-scan base-package = "**. common. log "> <context: include-filter type =" annotation "expression =" org. springframework. stereotype. controller "/> </context: component-scan>

It should be noted that the above configuration must be placed in the same xml file, either spring-mvc.xml or spring-context.xml, otherwise it may not take effect, and the reason is not found yet.

Annotation usage

@ XXXOperateLog (bussType = XXXSysConstant. BUSINESS_TYPE.YYYY, bussTypeDesc = "business type description", operateType = XXXSysConstant. logOperateType. QUERY, operateTypeDesc = "operation description") @ RequestMapping (value = "/**/queryXXXXX4DataGrid. json ", method = RequestMethod. POST) public void queryXXXXX4DataGrid (HttpServletRequest request, HttpServletResponse arg1, Model model, Writer writer) {logger.info ("========= ticket check (warehouse picking) transaction information start =============================== "); try {// do something for business} catch (SystemException se) {throw se;} catch (BusinessException be) {throw be;} catch (Exception e) {throw new SystemException (e );}}

In the above springMVC custom annotation, the method of using AOP to implement logging is all the content that I have shared with you. I hope to give you a reference, and I hope you can provide more support for the customer's house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.