preface

Before we mentioned AOP aspect programming in Spring, actually AOP is very practical in practical development, mastering AOP you will find the door to a new world, before learning AOP, you need to master the proxy pattern, which will not be explained in this article

Why use Spring AOP?

We all know that Spring AOP is also known as aspect oriented programming, we have only heard of OOP(object Oriented programming).

Take a look at this pseudocode:

Public Student queryStudent(int studentId){long startTime = system.currentTimemillis (); / / query Student information Student. Student = studentDao selectStudentInfo (studentId); Operationlog.add (); operationlog.add (); Long endTime = system.currentTimemillis (); // Calculate method execution time log.info(" execution time: "+ (endtime-starttime)); return student; }Copy the code

We can see that all the steps are not business code, except that querying the student information is business code.

In your daily work, if you encounter this kind of code, there are two solutions:

  • Extraction method
  • Extract the class

These two methods are called longitudinal extraction

Reviewing the fixed mode developed at ordinary times, Controller -> Service -> Dao, in this sequential execution, vertical extension of the execution logic no matter how to carry out the above two encapsulation, there will still be repeated code, take the above as an example: Even if logging method times and logging user action records are encapsulated as a method, this method is still attached to the method logic of our main business class

The upshot: vertical doesn’t solve these problems

This is where the AOP idea of this chapter comes in: take the same code scattered across the business logic code and extract it into separate modules in a horizontal cut

The extraction of code that is not part of the business logic into the aspect method for execution can be called horizontal extraction

Spring AOP principle

If I have been exposed to the proxy pattern before, I can see that the above horizontal extraction can be done through the proxy pattern, which uses a proxy class to enhance the behavior of objects, whereas the underlying principle of Spring AOP is dynamic proxies

Dynamic proxies are implemented in two ways in Java:

  • JDK dynamic proxy
  • Cglib dynamic proxy

JDK dynamic proxies are used by default in Spring AOP, and cglib proxies are used when proxy classes have no interfaces. Cglib proxies generate dynamic proxy objects that are subclasses of the target.

About the choice between JDK proxy and Cglib proxy, here are the recommendations given by Mastering Spring4.x Enterprise Application Development:

  • The cglib proxy is best used for singletons and JDK proxy is best used for multiple instances

The reasons are as follows:

  • The JDK performs better when creating proxy objects than the Cglib proxy, but it runs worse when generating proxy objects
  • If it is a singleton, Cglib is used

We can use the above knowledge sums up the Spring AOP: will the same logic of duplicated code transverse extraction, using dynamic proxy will duplicate code to merge into the method of implementation and the original method is the same function, so that we can write code trunk logic exist only in the business, without the need to care about has nothing to do with the business code.

Use of Spring AOP

Spring exists to date to provide support for three types of AOP:

  • Proxy-based Spring AOP: You need to implement interfaces and manually create proxies
  • POJO aspect: Use XML configuration, AOP namespace
  • @AspectAnnotation-driven facets: Use annotations for clarity

The @aspect approach implements AOP

Here’s how to implement AOP in the @aspect way. Let’s take a look at common annotations:

  • @aspect: Declares that this is a Aspect class and needs to be used with @Component, indicating that Spring is managing it

  • Pointcut: Define a Pointcut. There are two ways to express it:

    • Execution () matches the method
    • Annotation () matches annotations
  • @around: Enhancement processing, indicating surround enhancement, can be performed arbitrarily

  • @before: executed Before the pointcut method

  • @after: execute After method

  • @afterRETURNING: Similar to @After, but can capture the pointcut method return value for enhancement

  • AfterThrowing: executed when a method throws an exception

Here we use loop cutting as an example to write an AOP example that calculates method execution time:

@Aspect @Component public class TimeAspect { private static Logger log = Logger.getLogger(TimeAspect.class); @author liuhanchao */ @pointcut ("execution(*) com.test.service.. *. * (..) ) && (@ the annotation (org. Springframework. Web. Bind. The annotation. RequestMapping)) ") public void doPointcut () {} / * * * ring cutting method to calculate the execution time  * @param proceedingJoinPoint * @return * @throws Throwable */ @Around("doPointcut()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{ long startTime = System.currentTimeMillis(); / / get the method signature MethodSignature MethodSignature = (MethodSignature) proceedingJoinPoint. GetSignature (); / / get Method Method = methodSignature. GetMethod (); Object ret = ret=proceedingJoinPoint.proceed(); long endTime = System.currentTimeMillis(); log.info(method.getName()+" succ , time consuming: " + (endTime - startTime) + " ms"); return ret; }}Copy the code

conclusion

There are many knowledge points in Spring AOP, this article mainly from why to use, implementation principle, how to use? Three aspects are explained, and not too deep into the underlying source code, about Spring AOP in fact we only need to know in what case should be used, there are core knowledge points can

The following is a summary:

  • The underlying implementation of Spring AOP is dynamic proxy, which is divided into JDK dynamic proxy and Cglib dynamic proxy. Spring AOP uses JDK proxy by default, and uses Cglib proxy when the proxy class has no interface
  • The singleton chose the Cglib dynamic proxy because the Cglib proxy object runs faster than the JDK proxy object
  • Spinrg AOP is based on dynamic proxies, so it can only intercept methods

Common AOP usage scenarios:

  • Method execution time statistics
  • The log
  • permissions
  • .

At the end

Spring is going to have to write about loop dependency issues and SpringBoot auto-assembly issues. If you guys have anything you’d like to see, you can leave a comment below, so I can study it and communicate with you

Follow the public account logerJava to share more knowledge waiting for you to see