Feeling About Learning Spring AOP from cainiao

Source: Internet
Author: User

Feeling About Learning Spring AOP from cainiao

I. Introduction of spring AOP

AOP is Aspect-Oriented Programming called Aspect Oriented Programming. This is mainly proposed to achieve separation of non-logical businesses. For example, during programming, there are at least business logic-related code, non-business logic-related code, logs, and permissions, exception Handling and transaction processing. Before AOP came out, we had to mix these non-business logic codes in the business logic. As a result, it is conceivable that once the code volume increases to a certain level, it is particularly difficult to confuse and is not conducive to code maintenance, AOP is achieved by using the idea of code separation. We use the classic log record example to introduce the idea of AOP. Because every action in the business logic must be recorded, every business logic is logged. Assuming that according to the object-oriented idea, each object must have a log record, and each method must have the code for adding logs.

Public class Finance {Private Logger logger = Logger. getLogger (this. getClass (). getName (); Public void Accouting () {Logger. log (Level. INFO, "begin log"); // accouting action write the accounting code here ...... Logger. log (Level. INFO, "end log ");}}

In this way, there are many similar codes in multiple business logic, leading to redundancy. In order not to generate redundancy, we can think like this: how to separate the two codes? We want to separate the accounting code to achieve this.

(1) create an interface Finance

Public interface Finance{Public void Accouting();}

(2) implement this interface

Public class FinanceImpl implements Finance{Public void accouting(){……}}

(3) Compile a proxy class to implement business logic and log output.

Public class  FinanceProxy{Private Logger logger=Logger.getLogger(this.getClass().getName());Private FinanceImpl fi;Public FinanceProxy(FinanceImpl fi){This.fi=fi;}Public void Accouting(){Logger.log(Level.INFO,“begin log”);fi.accounting();Logger.log(Level.INFO,“end log”);}}

In this way, the business logic of the specific account is separated from the log information code. In the future, as long as this interface class is implemented, log information can be output through the agent class. In essence, the Code is not completely separated. If we want to create another proxy class for auditing, we have to create another proxy class for auditing, that is, the proxy class depends on the interface. In order to realize proxy class reuse, we can use the Java proxy mechanism to achieve further separation.


(1) Compile a log proxy class LoggerProxy to implement the Invocationhandler interface. As a result, logs can be output to any interface.


Public class  LoggerProxy implements InvocationHandler{Private Logger logger=Logger.getLogger(this.getClass().getName());Private object delegate;Public Object bind(Object delegate){This.delegate=delegate;Return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),delegate.getClass.getIntefaces(),this);}Public Object invoke(Object proxy,Method method,Object[]args)throws Throwable{Object result=null;Try{Logger.log(Level.INFO,“begin log”);Result=method.invoke(delegate,args);Logger.log(Level.INFO,“end log”);}catch(Exception e){……}}

(2) create an interface

Public interface Finance{Public void Accouting();}

(3) Implementation Interface

Public class FinanceImpl implements Finance{Public void accouting(){……}}

(4) Compile the test code

Public class FinanceTest {Public static void main (String [] args) {LoggerProxy lp = new LoggerProxy (); // The Next line of code can be changed as needed, to achieve reusable Finance fi = () lp. bind (new FinanceImpl ());}}

In this way, the next time we add auditing, we only need to add the code for auditing, and we do not need to rewrite the code for auditing.

Conclusion: This method is the idea of AOP, But we adopt the Java proxy mechanism to implement it. In fact, AOP is an idea, any technical implementation that complies with the idea of AOP can be seen as the implementation of AOP. From the above example, we can know that in AOP, the various business logic does not know that there is a log record monitoring it, that is, the implementation of each concern does not know whether there are other concerns concerned about it. This is not the case with OOP. We call AOP to regard some non-business logic as a plane. All calls to these business logic methods must go through this plane, this is the idea of AOP (the AOP implemented by the XML configuration file is actually a reflection of some code in the form of a configuration file, but a beautiful shell ).


A set of vce locations.

(2) Adivce: The processing logic used by a connection point, that is, the code injected into the connection point. The Code extracted from the preceding example to output logs is an Advice. Code added to jointPoint.

(3) Advisor is the configuration tool of PointCut and Advice. Is to inject Advice into the program Pointcut position code.

1. Entry point:

There are three methods to implement the entry point: static entry point, dynamic entry point, and custom entry point. Static entry points are limited to fixed-point methods and classes. You can specify parameters for a dynamic entry point. When the entry point needs to call the notification based on the parameter value during execution, a dynamic entry point is required. The dynamic entry point is rarely used, resulting in high performance loss.

2. Notification:

There are five types of notifications: Interception Around und, Before, After Returning, Throw, and Introduction. Before and after JointPoint, before JointPoint, and after JointPoint, when JointPoint throws an exception, after JointPoint is called.

(1) Interception und notification: The MethodInterceptor interface must be implemented for the cut surface.

(2) Before notification: The MethodBeforAdvice interface must be implemented for the aspect.

(3) After Returning notification: You need to implement the After ReturningAdvice interface.

(4) Throw notification: ThrowsAdvice must be implemented.

(5) Introduction notification: The IntroductionAdvisor and IntroductionInterceptor interfaces must be implemented.

3. provisioner: the code that injects Advice into the Pointcut position. It is usually used to configure Pointcut and Advice in XML mode.

(1) Use proxyFactorybean to proxy all methods of the target class or specified methods.

(2) The above five types of notifications can be used to complete the example of the preceding log.

Conclusion: Spring AOP can be implemented in three forms: Java Dynamic proxy, CGLIB proxy, and automatic proxy.


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.