Spring AOP custom annotation method to implement log management examples, springaop

Source: Internet
Author: User

Spring AOP custom annotation method to implement log management examples, springaop

We continue to implement AOP today. Here I personally think it is the most flexible and scalable method. In terms of log management, we use Spring AOP custom annotations to implement log management. Let's just get started !!!

I will repeat the configuration again.

The

<Mvc: annotation-driven/> <! -- Activate the component scan function. the components configured by annotation are automatically scanned under gcx and its sub-packages --> <context: component-scan base-package = "com. gcx "/> <! -- Start support for @ AspectJ annotation --> <! -- If proxy-target-class is equal to true, the cglib proxy is forcibly used, and the default value of proxy-target-class is false. If your class implements the interface, the JDK proxy is used. If no, go to cglib proxy --> <! -- Note: cglib proxy is recommended for standalone mode. Although JDK dynamic proxy is faster than cglib proxy, its performance is inferior to cglib --> <! -- If you do not enter proxy-target-class = "true", this statement is okay. --> <aop: aspectj-autoproxy proxy-target-class = "true"/> <! -- Cut section --> <bean id = "systemLogAspect" class = "com. gcx. annotation. SystemLogAspect"> </bean>

Next, write the code.

Create a log entity

public class SystemLog {  private String id;  private String description;  private String method;  private Long logType;  private String requestIp;  private String exceptioncode;  private String exceptionDetail;  private String params;  private String createBy;  private Date createDate;  public String getId() {    return id;  }  public void setId(String id) {    this.id = id == null ? null : id.trim();  }  public String getDescription() {    return description;  }  public void setDescription(String description) {    this.description = description == null ? null : description.trim();  }  public String getMethod() {    return method;  }  public void setMethod(String method) {    this.method = method == null ? null : method.trim();  }  public Long getLogType() {    return logType;  }  public void setLogType(Long logType) {    this.logType = logType;  }  public String getRequestIp() {    return requestIp;  }  public void setRequestIp(String requestIp) {    this.requestIp = requestIp == null ? null : requestIp.trim();  }  public String getExceptioncode() {    return exceptioncode;  }  public void setExceptioncode(String exceptioncode) {    this.exceptioncode = exceptioncode == null ? null : exceptioncode.trim();  }  public String getExceptionDetail() {    return exceptionDetail;  }  public void setExceptionDetail(String exceptionDetail) {    this.exceptionDetail = exceptionDetail == null ? null : exceptionDetail.trim();  }  public String getParams() {    return params;  }  public void setParams(String params) {    this.params = params == null ? null : params.trim();  }  public String getCreateBy() {    return createBy;  }  public void setCreateBy(String createBy) {    this.createBy = createBy == null ? null : createBy.trim();  }  public Date getCreateDate() {    return createDate;  }  public void setCreateDate(Date createDate) {    this.createDate = createDate;  }}

Write dao Interface

package com.gcx.dao;import com.gcx.entity.SystemLog;public interface SystemLogMapper {  int deleteByPrimaryKey(String id);  int insert(SystemLog record);  int insertSelective(SystemLog record);  SystemLog selectByPrimaryKey(String id);  int updateByPrimaryKeySelective(SystemLog record);  int updateByPrimaryKey(SystemLog record);}

Write service layer

package com.gcx.service;import com.gcx.entity.SystemLog;public interface SystemLogService {  int deleteSystemLog(String id);  int insert(SystemLog record);    int insertTest(SystemLog record);  SystemLog selectSystemLog(String id);    int updateSystemLog(SystemLog record);}

Write service implementation class serviceImpl

package com.gcx.service.impl;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.gcx.annotation.Log;import com.gcx.dao.SystemLogMapper;import com.gcx.entity.SystemLog;import com.gcx.service.SystemLogService;@Service("systemLogService")public class SystemLogServiceImpl implements SystemLogService {  @Resource  private SystemLogMapper systemLogMapper;    @Override  public int deleteSystemLog(String id) {        return systemLogMapper.deleteByPrimaryKey(id);  }  @Override    public int insert(SystemLog record) {        return systemLogMapper.insertSelective(record);  }  @Override  public SystemLog selectSystemLog(String id) {        return systemLogMapper.selectByPrimaryKey(id);  }  @Override  public int updateSystemLog(SystemLog record) {        return systemLogMapper.updateByPrimaryKeySelective(record);  }  @Override  public int insertTest(SystemLog record) {        return systemLogMapper.insert(record);  }}

The basic program has been compiled.

Start the custom annotation below

Package com. gcx. annotation; import java. lang. annotation. *; @ Target ({ElementType. PARAMETER, ElementType. METHOD}) @ Retention (RetentionPolicy. RUNTIME) @ brief ented public @ interface Log {/** operation type to be executed, such as: add operation **/public String operationType () default ""; /** specific operations to be performed, such as: adding a user **/public String operationName () default "";}

Write the section below

Package com. gcx. annotation; import java. lang. reflect. method; import java. util. date; import java. util. UUID; import javax. annotation. resource; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpSession; import org. aspectj. lang. joinPoint; import org. aspectj. lang. proceedingJoinPoint; import org. aspectj. lang. annotation. after; import org. aspectj. lang. annotation. afterReturning; import org. as Pectj. lang. annotation. afterThrowing; import org. aspectj. lang. annotation. around; import org. aspectj. lang. annotation. aspect; import org. aspectj. lang. annotation. before; import org. aspectj. lang. annotation. pointcut; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springframework. stereotype. component; import com. gcx. entity. systemLog; import com. gcx. entity. user; import com. gcx. service. systemLog Service; import com. gcx. util. jsonUtil;/*** @ author Yang Jian * @ E-mail: email * @ version Creation Time: 4:29:05 * @ desc cut class */@ Aspect @ Componentpublic class SystemLogAspect {// inject Service to save the Log Database @ Resource // here I use resource annotation, generally, @ Autowired is used. If they have time, I will write private SystemLogService systemLogService in my blog; private static final Logger logger = LoggerFactory. getLogger (SystemLogAspect. class); // Controller layer cut point @ Pointcut ("execution (* com. gcx. controller .. *. *(..)) ") public void controllerAspect () {}/ *** pre-notification is used to intercept the Controller layer to record user operations ** @ param joinPoint cut point */@ Before (" controllerAspect ()") public void doBefore (JoinPoint joinPoint) {System. out. println ("=========== execute controller pre-notification ======================"); if (logger. isInfoEnabled () {logger.info ("before" + joinPoint) ;}// configure the controller surround notification, using the entry point registered on method aspect @ Around ("controllerAspect ()") public void around (JoinPoint joinPoint) {System. out. println ("=========== start to execute the controller surround notification ==================== "); long start = System. currentTimeMillis (); try {(ProceedingJoinPoint) joinPoint ). proceed (); long end = System. currentTimeMillis (); if (logger. isInfoEnabled () {logger.info ("around" + joinPoint + "\ tUse time:" + (end-start) + "MS! ");} System. out. println ("=========== end execution controller surround notification ======================== ");} catch (Throwable e) {long end = System. currentTimeMillis (); if (logger. isInfoEnabled () {logger.info ("around" + joinPoint + "\ tUse time:" + (end-start) + "MS with exception:" + e. getMessage () ;}}/ *** post-notification is used to intercept the Controller layer to record user operations ** @ param joinPoint ing */@ After ("controllerAspect ()") public void after (JoinPoint JoinPoint) {/* HttpServletRequest request = (ServletRequestAttributes) RequestContextHolder. getRequestAttributes ()). getRequest (); HttpSession session = request. getSession (); * // read the User in the session // user User = (User) session. getAttribute ("user"); // request IP // String ip = request. getRemoteAddr (); User user User = new user (); User. setId (1); user. setName ("Zhang San"); String ip = "127.0.0.1"; try {String targetNam E = joinPoint. getTarget (). getClass (). getName (); String methodName = joinPoint. getSignature (). getName (); Object [] arguments = joinPoint. getArgs (); Class targetClass = Class. forName (targetName); Method [] methods = targetClass. getMethods (); String operationType = ""; String operationName = ""; for (Method method: methods) {if (method. getName (). equals (methodName) {Class [] clazzs = method. getParame TerTypes (); if (clazzs. length = arguments. length) {operationType = method. getAnnotation (Log. class ). operationType (); operationName = method. getAnnotation (Log. class ). operationName (); break ;}}// * ========= console output =============* // System. out. println ("===== controller post-Notification start ===="); System. out. println ("Request Method:" + (joinPoint. getTarget (). getClass (). getName () + ". "+ joinPoint. getSignature (). getName () + "()") +". "+ OperationType); System. out. println ("method Description:" + operationName); System. out. println ("requester:" + user. getName (); System. out. println ("request IP:" + ip ); // * ========= Database log =============* // SystemLog log = new SystemLog (); log. setId (UUID. randomUUID (). toString (); log. setDescription (operationName); log. setMethod (joinPoint. getTarget (). getClass (). getName () + ". "+ joinPoint. getSignature (). getName () + "()") + ". "+ operat IonType); log. setLogType (long) 0); log. setRequestIp (ip); log. setExceptioncode (null); log. setExceptionDetail (null); log. setParams (null); log. setCreateBy (user. getName (); log. setCreateDate (new Date (); // Save the systemLogService database. insert (log); System. out. println ("===== controller post-Notification end ====");} catch (Exception e) {// record the local Exception log logger. error ("= post-Notification exception ="); logger. error ("exception information: {}", e. getMessage ());}}/ /Configure the post-return notification. Use the entry point registered on method aspect () @ AfterReturning ("controllerAspect ()") public void afterReturn (JoinPoint joinPoint) {System. out. println ("===== notification of post-execution controller return ===="); if (logger. isInfoEnabled () {logger.info ("afterReturn" + joinPoint );}} /*** exception notification is used to intercept abnormal logs ** @ param joinPoint * @ param e */@ AfterThrowing (pointcut = "controllerAspect ()", throwing = "e ") public void doAfterThrowing (JoinPoint joi NPoint, Throwable e) {/* HttpServletRequest request = (ServletRequestAttributes) RequestContextHolder. getRequestAttributes ()). getRequest (); HttpSession session = request. getSession (); // read the User user User = (User) session in the session. getAttribute (WebConstants. CURRENT_USER); // obtain the request ip String ip address = request. getRemoteAddr (); * // obtain the parameters of the User request method and serialize them to a JSON string user User = new user (); User. setId (1); user. setName ("Zhang 3 "); String ip =" 127.0.0.1 "; String params =" "; if (joinPoint. getArgs ()! = Null & joinPoint. getArgs (). length> 0) {for (int I = 0; I <joinPoint. getArgs (). length; I ++) {params + = JsonUtil. getJsonStr (joinPoint. getArgs () [I]) + ";" ;}} try {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 operationType = ""; String operationName = ""; for (Method method: methods) {if (method. getName (). equals (methodName) {Class [] clazzs = method. getParameterTypes (); if (clazzs. length = arguments. length) {operationType = method. getAnnotation (Log. class ). operationType (); operationName = method. getAnnotation (Log. class ). operationName (); break ;}}/ * ======= console output ============= */System. out. println ("===== exception notification start ===="); System. out. println ("Exception Code:" + e. getClass (). getName (); System. out. println ("exception information:" + e. getMessage (); System. out. println ("exception method:" + (joinPoint. getTarget (). getClass (). getName () + ". "+ joinPoint. getSignature (). getName () + "()") + ". "+ operationType); System. out. println ("method Description:" + operationName); System. out. println ("requester:" + user. getName (); System. out. println ("request IP:" + ip); System. out. println ("request parameter:" + params ); /* =========== Database log =============*/SystemLog log = new SystemLog (); log. setId (UUID. randomUUID (). toString (); log. setDescription (operationName); log. setExceptioncode (e. getClass (). getName (); log. setLogType (long) 1); log. setExceptionDetail (e. getMessage (); log. setMethod (joinPoint. getTarget (). getClass (). getName () + ". "+ joinPoint. getSignature (). getName () + "()"); log. setParams (params); log. setCreateBy (user. getName (); log. setCreateDate (new Date (); log. setRequestIp (ip); // Save the systemLogService database. insert (log); System. out. println ("===== Exception notification end ====");} catch (Exception ex) {// record the local Exception log logger. error ("= Exception notification exception ="); logger. error ("exception message: {}", ex. getMessage () ;}/ * ===========record the local exception log ===========*/logger. error ("exception method: {} Exception Code: {} exception information: {} parameter: {}", joinPoint. getTarget (). getClass (). getName () + joinPoint. getSignature (). getName (), e. getClass (). getName (), e. getMessage (), params );}}

I have written a lot of information here, including pre-notifications, surround notifications, post-notifications, exception notifications, and post-meal notifications. It's okay if we don't write them all in our actual writing, I used to write the logging logic in the Post-notification. I think there are some pre-notifications on the Internet, but I feel it is better to write them in the post-notification.

Add custom annotations to the controller !!

Package com. gcx. controller; import org. springframework. beans. factory. annotation. autowired; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. requestMapping; import com. gcx. annotation. log; import com. gcx. service. userService; @ Controller @ RequestMapping ("userController") public class UserController {@ Autowired private UserService userService; @ RequestMapping ("testAOP") @ Log (operationType = "add operation :", operationName = "Add User") public void testAOP (String userName, String password) {userService. addUser (userName, password );}}

Write the test class below

@ Test public void testAOP1 () {// start Spring container ApplicationContext ctx = new ClassPathXmlApplicationContext (new String [] {"classpath: applicationContext-mvc.xml", "classpath: applicationContext-dataSource.xml "}); // obtain service or controller component UserController userController = (UserController) ctx. getBean ("userController"); userController. testAOP ("zhangsan", "123456 ");}

Database Data:

I originally wanted to write two cut points, one is the service layer, the other is the controller layer, the service layer is used to record abnormal information logs, and the controller layer is used to record functional logs, the running result is as follows.

In this case, you do not know whether the running efficiency is good in the actual project. Here you can see some suggestions from the blog !!

The above example of implementing log management by using spring AOP custom annotation is all the content that I have shared with you. I hope you can give us a reference and also hope you can provide more support.

Related Article

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.