Spring-boot use AOP for unified processing of logs _java

Source: Internet
Author: User

AOP I think it's clear to all of us that sometimes we need to process some of the request logs, or we can monitor some of the methods, and if there are exceptions that should be handled, now we're introducing AOP from Spring-boot.

[Development environment: JDK version number is 1.8,spring
The version number of boot is 1.4.1]{style= "Background-color: #FF0000"}

First, we first introduce the jar package,

The Pom file adds the following:

<!--quotes aop-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  < artifactid>spring-boot-starter-aop</artifactid>
</dependency>
<!--reference Gson for printing-->
<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson< /artifactid>
  <version>2.7</version>
</dependency>

After introducing the jar package, we started the boot method with two simple request processing methods:

@SpringBootApplication (scanbasepackages = {"com"})
@RestController public
class demoapplication{
  public static void Main (string[] args) {
   springapplication.run (demoapplication.class, args);
  Tests the parameterless GET request
  @RequestMapping (value = "/testaspect", method = requestmethod.get) public
  Uservo test () {
   Uservo Uservo = new Uservo ();
   Uservo.setage ("the");
   Uservo.setname ("He Xiao Five");
   Uservo.setsex ("male");
   return uservo;
  }
  Test for a parameter get request, let AOP print parameter content
  @RequestMapping (value = "/testaspectargs", method = Requestmethod.get)
  public Uservo Test (String name,string age,string sex) {
   Uservo Uservo = new Uservo ();
   Uservo.setname (name);
   Uservo.setage (age);
   Uservo.setsex (sex);
   return Uservo;
  }

After adding two simple processing request methods, we will increase our AOP

/** * Project Name: Springbootdemo * Creator: He Xiao * creation time: 16/12/4 7:05 * Class Name: Aspectdemo * Class Description://declaration is a slice @Aspect//statement is a spring management
  Bean @Component @Order (1) public class Aspectdemo {private Logger log = Logger.getlogger (GetClass ());
  Private Gson Gson = new Gson ();
  Stating that a tangent is inside the execution expression @Pointcut ("Execution (public * com.example.demoapplication.* (..))") A private void Controlleraspect () {}//Request method prints the content before @Before (value = "controlleraspect ()") public void Methodbefore (Joi Npoint joinpoint) {servletrequestattributes requestattributes = (servletrequestattributes)
   Requestcontextholder.getrequestattributes ();
   HttpServletRequest request = Requestattributes.getrequest ();
   Print request Content Log.info ("=============== request Content ===============");
   Log.info ("Request Address:" +request.getrequesturl (). toString ());
   Log.info ("Request Way:" +request.getmethod ());
   Log.info ("Request class Method:" +joinpoint.getsignature ());
   Log.info ("Request class method parameter:" + arrays.tostring (Joinpoint.getargs ())); Log.info ("=============== Request content ==============="); (returning = "O", Pointcut = "controlleraspect ()") public void methodafterreturing After the completion of the method:
   Object o) {log.info ("--------------return content----------------");
   Log.info ("Response content:" +gson.tojson (o));
  Log.info ("--------------return----------------");
 }

After the two are configured, next, we request, and then look at the print log, first of all, start our container, and then we first request a parameter processing request method, the print log is as follows:

{width= "1232"
height= "132"}

It can be found that the requested Url,method, as well as the value of the args parameter, and the type, as well as the returned content, are printed, indicating that the AOP interception was successful.

Next, we test the request method with no parameters, the print log is as follows:

{width= "1100"
Height= "130"}

We can see that this method, the printed method parameter is an empty array, because the method does not require parameter passing.

The above is springboot reference AOP for processing the Web log processing, the following will add the AOP section of the main notes, the following is only the description of the annotation and use, the specific test, the author will not be tested, you reader interested, you can test yourself:

class Annotation:

@Aspect define a class as a slice class
@order (i) to mark the processing priority of the slice class, the smaller I value, the higher the priority level. PS: You can annotate classes and annotate methods

Method Annotation:

@Pointcut Define a method for a tangent to the contents of an expression, described in detail below
@Before Executes the method before the tangent point, which is the specified tangent
@After After the pointcut, return before return execution,
@AfterReturning is executed after the pointcut, return, and if you want to handle some of the returned parameters of the method, you can
@Around The wrapping point, followed by the tangent point before entering the tangent
@AfterThrowing Throw an exception after the pointcut is processed
@order (i) to mark the precedence of pointcuts, the smaller I, the higher the precedence

Use @Pointcut annotation combinations:

In the code above, we define a pointcut that handles only the specified path:

@Pointcut ("Execution (public * com.example.demoapplication.* (..))")
private void Controlleraspect () {}

Now, we're defining a pointcut that handles other paths:

@Pointcut ("Execution (public * com.demo.*.* (..))")
private void Controllerdemo () {}

The pointcuts above are handled differently, and if we need a pointcut to handle both of them, we can configure this:

@Pointcut (value = "Controlleraspect" () | | Controllerdemo () ")
private void All () {}

In the @pointcut annotation, refer directly to other method names that have been @pointcut annotated so that the pointcut can handle methods under two paths

Execution expressions in @Pointcut annotations: public * com.demo.*.* (..)

The first public represents the modifier for the method, which can be replaced with *
The first * represents the return value, * represents all
com.demo.* package Path,. * Indicates all packages under the path
The third. * Represents a method for all classes under the path under all packages
(..) Represents an unlimited method parameter

Some caveats about @order(i) Note:

Annotation class, I value is, the smaller the value, the higher the priority
Annotation method, divided into two kinds of cases
Annotation is @Before is the smaller I value, the higher the priority
Note is @After or @afterreturning, the greater I value, the higher the priority

The summary of the two is:
Operation before pointcut, by order value from small to large execution
Action after pointcut, by the value of the order from large to small

Extended:

There is a reader may ask if I want to print requests from, to the end, the time required to define a member variable, used to statistic time, and give @before and @afterreturning access, there may be synchronization problems, So we refer to a Threadlocal object that specifies the generic, @before the time that the request is recorded, and the time it takes to deduct the record in @afterreturning, the code is as follows:

/** * Project Name: Springbootdemo * Creator: He Xiao * creation time: 16/12/4 7:05 * Class Name: Aspectdemo * Class Description://declaration is a slice @Aspect//statement is a spring management
  Bean @Component @Order (1) public class Aspectdemo {private Logger log = Logger.getlogger (GetClass ());
  Private Gson Gson = new Gson ();
  threadlocal<long> starttime = new threadlocal<long> ();
  Stating that a tangent is inside the execution expression @Pointcut ("Execution (public * com.example.demoapplication.* (..))") A private void Controlleraspect () {}///Request method prints the content before @Before (value = "controlleraspect ()") public void Methodbefore (Joinpoint joinpoint)
   {Starttime.set (System.currenttimemillis ()); Servletrequestattributes requestattributes = (servletrequestattributes) requestcontextholder.getrequestattributes (
   );
   HttpServletRequest request = Requestattributes.getrequest ();
   Print request Content Log.info ("=============== request Content ===============");
   Log.info ("Request address:" + request.getrequesturl (). toString ());
   Log.info ("Request way:" + Request.getmethod ()); Log.info ("Request class Method:" + JoinpoInt.getsignature ());
   Log.info ("Request class method parameter:" + arrays.tostring (Joinpoint.getargs ()));
  Log.info ("=============== request Content ==============="); (returning = "O", Pointcut = "controlleraspect ()") public void methodafterreturing After the method execution is completed @AfterReturning (Object o)
   {Log.info ("--------------return content----------------");
   Log.info ("Response content:" + Gson.tojson (o));
   Log.info ("--------------return----------------");
  Log.info ("Request Processing time is:" + (System.currenttimemillis ()-Starttime.get ()));
 }
}

Above, are the results of my test, may be inconsistent, or wrong, welcome correction.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.