Dry goods have quality, hydrology has feelings, wechat search [program control], pay attention to this interesting soul

preface

In this article, we will learn about another important feature of Spring, AOP, and its proxy feature

Static proxy is represented by AspectJ. Dynamic proxy is divided into JDK dynamic proxy and Cglib dynamic proxy.

Wet elder brother this B, this is to make an affair, on one section just said not to notice too much noun, this section come up to give me whole so much noun, disliking my brain too good make be? So let me show you a picture of that

Joke, little brothers don’t worry, the above is to let you familiar with the noun, have an impression, then I will slowly introduce to you, touch gently, afraid of pain, yao Yao ~~

AOP overview

AOP, section-oriented programming, in a word, extracts some common, business-independent functional code and inserts it dynamically into business methods at run time.

Here’s an example:We now have many business methods, such as add(), delete(), get(), etc. In each of these methods, there are transaction on and transaction off operations.

This code is repetitive, and we can extract this code. If we optimized it purely using OOP object-oriented thinking, it would look something like this:

This way even though our code looks less, but what? The delete(), get(), and other methods have repetitive code for starting and closing transactions.

This is where AOP comes in and we can enhance objects by dynamic proxies, writing non-business code on the logic to be enhanced. We will introduce the underlying implementation of dynamic proxy

Take another example: now there is a system with a lot of logical functions have been written online, the customer put forward a new requirement, in each method call should write log, incidentally write in the database (last week Brother Shi met a similar customer ~~)

Do how? You can’t find every business method; it’s too cumbersome to add them one by one in the business code.

You are smart enough to think of a way, AOP ah, directly to the aspect, the method through dynamic proxy enhancement, so that you do not have to modify the original business logic.

So far, with a brief understanding of AOP’s thinking and role, we can simply conclude that:

  • The idea of AOP is faceted programming, untangling the internals of objects and influencing functionality in enhanced ways

  • AOP is a horizontal relationship that reduces coupling between modules and extracts common code parts

Spring AOP addresses object enhancement. New features are enhanced without changing the original logic, opening up a new Angle in the form of sections.

The basic concepts of Spring AOP are:

  • Aspect: Usually a class in which pointcuts and advice can be defined

  • JointPoint: An explicit point in the execution of a program, usually a method call

  • Advice: Enhanced processing performed at pointcuts, such as before, after, and so on

  • Pointcut: Join points with advice, primarily for writing Pointcut expressions in a program

There are several types of notification methods:

  • Pre-notification (@before): Run Before we execute the target method

  • Post notification (@after): After our target method has finished running, exception or no exception

  • Return notification (@afterRETURNING): Runs after the target method returns a value normally

  • Exception Notification (@afterThrowing): Runs after an exception occurs in the target method

  • Surround Notification (@around): You need to manually execute JoinPoint.procced (), a combination of pre-notification and post-notification

Static agent

Proxy, a design pattern that provides access to target objects through proxies, can be enhanced based on the implementation of target objects.

An example of static proxy ~ :

Now there is an interface User with the save() method; An implementation class, UserImpl, implements the User interface to store data; Now I want to add open and close transactions to its data saving operation, of course we can add it directly to the business code.

But what if there are so many ways to add now?

So we found a proxy object, which is also the implementation class of the User interface, and contains the property object UserImpl, as follows:

In this way, a lot of public work can be entrusted to the agent to do, do not have to do

Let’s expand on AspectJ’s knowledge:

AspectJ is a language-level IMPLEMENTATION of AOP that extends the Java language, defines AOP syntax, and provides cross-cutting code weaving at compile-time, so it has a compiler dedicated to generating Class files that comply with the Java bytecode specification.

Static proxies have disadvantages:

  • If the interface is changed, the proxy needs to be modified, which is more troublesome

  • The proxy object needs the same interface as the target implementation, and there are many interface implementation class objects

Now let’s see how dynamic proxy does ~

A dynamic proxy

Spring AOP is the underlying dynamic proxy, there are two implementations: JDK dynamic proxy and CGlib dynamic proxy.

Source “master spring4.x enterprise application development combat” a paragraph:

Implemented using pure Java, Spring AOP does not require a special compilation process or a special class loader, and it proxies enhanced code into target classes at run time. Spring AOP, IoC, and AspectJ can be seamlessly integrated in Spring.

Spring AOP is built on dynamic proxies, so Spring’s support for AOP is limited to method interception. What does that mean? Enhancements only go to the method level, not the code block level.

JDK dynamic proxy

JDK dynamic proxies receive proxied classes through reflection and require that the proxied classes implement an interface. At the heart of JDK dynamic proxies are the InvocationHandler interface and Proxy class. Spring AOP uses JDK dynamic proxies by default. Let’s look at the following code:

Test the effect:

Wet brother, you fuck me, come up and do a bunch of don’t know the code look shit, you are not my wet brother anymore.

So, yes, I have changed, become more tired of love than before, wood ~

Next to explain to you:

Proxy.newproxyinstance is a dynamic Proxy provided by the JDK. The parameters passed in are the class loader to enhance the class, its interface, and an InvocationHandler object whose invoke() function can be used to implement the enhancement.

The JDK dynamic proxy base is enhanced by modifying the bytecode of the entity-class object Class file.

Two common questions: Why are JDK dynamic proxies implemented based on interfaces, rather than inheritance? In JDK dynamic proxy, does the target object call another method of its own, passing through the proxy object?

You can think for yourself ~~

First, why interface based implementation?

Dynamic proxy objects inherit from proxy objects by default, and Java does not support multiple inheritance, so JDK proxies are implemented based on interfaces.

Second, will the target object call the rest of the methods and call the proxy object?

The answer is no, the internal call is equal to this.a (), where this refers to the original object, not the proxy object, so method A is not enhanced.

CGlib dynamic proxy

Since JDK dynamic proxies require an interface to implement enhancements, which we may not have in development, AOP defaults to the CGlib dynamic proxy implementation.

The CGlib agent, also known as a subclass agent, builds a subclass from memory to extend the functionality of the target object.

CGLIB is a powerful, high-performance code generation package that extends Java classes and implements Java interfaces at run time. It is widely used by many AOP frameworks, such as Spring AOP and Dynaop, to provide methods for interception.

Directly points to introduce:

  • For example, the Spring core package already includes CGlib functionality, so you can directly introduce the spring-core-3.2.5. jar package

  • The class of the agent cannot be final, otherwise an error will be reported.

  • If the methods of the target object are final/static, they are not intercepted, that is, no additional business methods of the target object are executed.

CGlib was used to compensate for the JDK’s lack of dynamic proxies (proxy objects must implement interfaces);

omg

The more you know, the more you don’t know.

Suggestion: IOC and AOP in Spring are basic, important, and interview favorites

If you feel good about it, you can follow my wechat public account [Program control]. Brother Shih has always insisted on sharing technical articles with everyone, so that everyone can be quietly top of the list and then surprise everyone