Simple and straightforward understanding of AOP, understanding of Spring AOP, and using AspectJ

Source: Internet
Author: User

AOP = Aspect Oriental Programing for Aspect-Oriented Programming

The article does not talk about AOP terms, such as connection points, cut points, and cut points. It is too difficult to remember. It aims to understand AOP in a simple and straightforward way, understand Spring AOP, and apply AspectJ.

 

1. What is AOP?

 

 

 

 

From the vertical perspective, methods 1, 2, and 3 All execute the same A and B code, so it is boring to repeat the code.

A typical scenario is to start transactions, update table data, commit transactions, start transactions, delete table data, and submit transactions.

So we can extract the repeated code from the horizontal perspective

A B
A A
Method 1 (Code x) Method 2 (Code y) Method 3 (Code z)
B B

 

 

 

 

AOP wants to distribute the same code A and B in various business logic, extract them to an independent module by means of horizontal cutting, and make the business logic Class A fresh world.

Of course, it is easy to separate the repetitive cross-cutting logic. However, this is the key and the main problem to be solved by AOP.

 

2. Spring AOP Implementation Mechanism

Spring AOP uses dynamic proxy technology to weave enhanced code at runtime and uses two proxy mechanisms ,.

Weaving and enhancement are two terms of AOP. The simple point of weaving enhancement code is to insert another piece of code on your code.

It mainly involves two classes in the java. lang. reflect package: Proxy and InvocationHandler (interface ).

Directly Add code

Add (x,CalcService interface CalcServiceImpl add (x, "Result:" + (x +CalcServiceImpl implementation class CalcHandler. target = Object invoke (Object proxy, Method method, Object [] args) "******** run the code before calling the method ******" = Method. invoke ("******** run the code after calling the method ******"CalcHandler implements InvocationHandler

The execution result is

 

However, JDK dynamic proxy has a limitation that it can only create proxy instances for interfaces.

View the Proxy method newProxyInstance (ClassLoader loader, Class <?> [] Interfaces, InvocationHandler h)

Interfaces is the list of interfaces that require proxy instances.

CalcProxy Enhancer enhancer = enhancer. setCallback (enhancer. create (); Object intercept (Object obj, Method method, Object [] args, MethodProxy proxy) "******* run the code before calling the method *******" = proxy. invokeSuper (obj, args); System. out. println ("******** execute the code after calling the method ******"CalcProxy implements the MethodInterceptor interface = (CalcServiceImpl) proxy. getProxy (CalcServiceImpl.2, 3Test2 test class

 

Then we made an efficiency comparison between the two.

On my local machine, I recorded the two through System. nanoTime (). The result is as follows:

 

A creation takes a long time and an execution time.

 

3. Use Spring AOP and configure it through XML

In Spring, the AopProxy interface is defined and two final implementation classes are provided.

Cglib2AopProxy JdkDynamicAopProxy

Take a pre-enhancement as an example, that is, the Code executed before the execution of the target method.

CalcBeforeAdvice before (Method method, Object [] args, Object obj) "******* run the code before calling the target method ******" = ProxyFactory pf = pf. setInterfaces (target. getClass (). getInterfaces (); pf. setOptimize (); pf. setProxyTargetClass (); = 2, 3Implement pre-enhancement through Spring

The above uses ProxyFactory to create a proxy. Next we declare the proxy through Spring configuration.

 

In addition to the pre-enhancement BeforeAdvice, the post-enhancement AfterReturningAdvice, surround enhancement MethodInterceptor, and exception throw enhancement are also available.

ThrowsAdvice and IntroductionInterceptor are both interfaces.

Here, the introduction enhancement is slightly emphasized. It will add some new methods and attributes to the target class.

 

At this point, I may have a little understanding of AOP. Let's briefly talk about several terms of AOP. (didn't you say you don't want to talk about them ......)

: These specific points are called connection points after a method throws an exception before or after the class is initialized, before or after the method is called. : Think about database queries. The cut point is to find the corresponding connection point through the conditions set by the database. : Add the code to a connection point. : A special enhancement. It adds some attributes and methods to the class. If A service class does not implement the interface, we add A method to it to make it an implementation class of. : Is how to add the enhancement to the connection point. Three Ways of weaving: 1. during compilation, special JAVA compilers are required. 2. during the class loading period, special class loaders are required. dynamic proxy weaving, adding enhanced Spring for the target class at runtime adopts dynamic proxy, while AspectJ adopts compiling and class loading. : Your Own Business class. AOP is used to enhance and introduce this class. : The result class generated after the target object is woven into the enhancement. : Composed of cut points and enhancement (introduced). Spring AOP is the framework responsible for implementing cut-plane. It defines the cut-plane logic (that is, the Code) it is woven into the connection point specified by the plane (that is, where the code is added.

After reading the nouns and the previous code, we found that the enhancement was woven into all the methods of the target class (XX has a choice ....)

Now we need to woven enhancement to some methods of some classes, then the concept of cut points is involved.

AddAdvisor 0 = "add" = ProxyFactory pf = pf. setInterfaces (target. getClass (). getInterfaces (); pf. setOptimize (); pf. setProxyTargetClass (); AddAdvisor advisor = CalcService proxy = 2, 3AddAdvisor inherits StaticMethodMatcherPointcutAdvisor

Define the aspect through Spring Configuration

// CalcServiceImpl proxy

 

The above is troublesome. We use a static regular expression to match

                .add*    

Spring provides six types of cut points: static method cut points, dynamic method cut points, annotation cut points, expression cut points, and process cut points. I have limited capabilities and have not studied them, just use the static cut point StaticMethodMatcherPointcut to make an example. When the project is used, study it again.

 

4. Use AspectJ

The Spring AOP application is quite troublesome. Do you have a headache when writing the XML description to implement this interface?

The @ AspectJ annotation can easily define a plane without any interface.

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.