Java programmers go from stupid birds to cainiao () to talk about spring (5)'s bottom layer of AOP

Source: Internet
Author: User

As we all know, Java is a powerful representative of object-oriented language. When we mention Java, we will immediately think of object-oriented, and when we mention object-oriented, we will think of Java. However, object-oriented is not perfect, and it focuses more on Object hierarchies. There are still some shortcomings in how to better manage the internal structure of object behavior. So how can we solve this problem more perfectly? The answer is AOP.

AOP: Aspect-Oriented Programming. AOP is a supplement to OOP and a continuation of gof. We know that the design mode is a summary of the experience in object-oriented design. What it constantly pursues is the decoupling between the caller and the called. With the design model, we can make more effective use of the object-oriented features, making the entire software design more flexible and elegant. However, the design pattern is based on the object-oriented idea. More often, it focuses on Object-level things, but it has some shortcomings in solving internal problems of object behavior. The emergence of AOP is precisely a perfect supplement to the object-oriented thinking.

Speaking of AOP, we have to raise the vertical and horizontal problems of the software. From the perspective of vertical structure, each module of our software system is mainly responsible for processing our core business (such as product ordering and shopping cart viewing). From the perspective of horizontal structure, almost every system contains some public modules (such as permissions and log modules ). These public modules are distributed in each of our core businesses (for example, the process of ordering and viewing product details must check user permissions and record system logs ). In this way, not only do we need to focus on the processing of Public modules in the development process, but it is also very troublesome to maintain them after development. With AOP, the business logic in the application is separated from the general services that it supports, allowing developers to focus more on core business development.


Let's take a simple example to look at AOP! For example, there are many business methods in an application to be developed. However, we need to perform comprehensive monitoring or partial monitoring on the implementation of this method. maybe we will add a log record before some methods. Let's write an example to see our simplest solution.
First, write the ihello. Java code of the interface as follows:

Public interface ihello {/*** // *** assume this is a business method * @ Param name */void sayhello (string name );}

There is a method used to input the name "hello" added in; Let's write a class to implement the ihello interface.


public class Helloimplements IHello{public void sayHello(String name){System.out.println("Hello" + name);}}

Now we need to add a log-recorded business for this business method. What can we do without changing the original code? Maybe, you will write a class to implement the ihello interface and rely on the class hello. The Code is as follows:

public class HelloProxyimplements IHello{ private IHello hello;  public HelloProxy(IHello hello){ this.hello= hello;  } public void sayHello(String name){ Logger.logging(Level.DEBUGE,"sayHello method start."); hello.sayHello(name); Logger.logging(Level.INFO,"sayHello method end!"); }}

From the code above, we can see that the hello object is created by the so-called proxy state helloproxy. in this way, if we want to remove the logging function in the future. we only need to change the specific implementation of the "hello" object to "hello. The above code is the simplest line of sight for AOP, but next we will think that if we want to add logs before many business logic, then, are we going to write many classes like helloproxy. yes, yes. it is also a very troublesome task. after jdk1.3. JDK provides an API Java with us. lang. reflect. invocationhandler class. this class allows us to do something dynamic for some methods when JVM calls a class method. let's change the above Code to see the effect.

Similarly, we write an ihello interface and a hello implementation class. In the interface, we define two methods. The Code is as follows:

Ihello. Java

Package sinosoft. DJ. AOP. proxyaop; public interface ihello {/*** // *** business processing method A * @ Param name */void sayhello (string name ); /*** // *** business processing method B * @ Param name */void saygoogbye (string name );}

Hello. Java

package sinosoft.dj.aop.proxyaop;  public class Helloimplements IHello{  public void sayHello(String name){  System.out.println("Hello" + name);  } public void sayGoogBye(String name){ System.out.println(name+" GoodBye!"); }}


Let's write a proxy class in the same way. Let this class implement the java. Lang. Reflect. invocationhandler interface. The Code is as follows:

Package sinosoft. DJ. AOP. proxyaop; import Java. lang. reflect. invocationhandler; import Java. lang. reflect. method; import Java. lang. reflect. proxy; public class dynaproxyhelloimplements invocationhandler {/***** // *** the object to be processed (that is, we need to add the business logic object before and after the method, such as hello in the example) */private object delegate;/***** // *** the object after the dynamic generation method is processed (fixed) ** @ Param delegate * @ Param proxy * @ return */public object BIND (Object delegate) {This. deltas Te = delegate; return proxy. newproxyinstance (this. delegate. getclass (). getclassloader (), this. delegate. getclass (). getinterfaces (), this);}/***** // each method in the object to be processed will be sent to the JVM for calling this method, that is, the method of the object to be processed can only be called through this method * This method is dynamic, not manually called */public object invoke (Object proxy, method, object [] ARGs) throws throwable {object result = NULL; try {// log logger before executing the original method. logging (level. debuge, method. getname () + "method end." ); // JVM executes the original method (reflection mechanism) Result = method through this statement. invoke (this. delegate, argS); // logs logger after the original method is executed. logging (level. info, method. getname () + "method start! ");} Catch (exception e) {e. printstacktrace ();} // return the method return value to the caller: return result ;}}


We can see from the above example. as long as you adopt interface-oriented programming, you can add the operations that record logs before executing any object method. he (dynapoxyhello) automatically goes to the proxy to execute every method in the proxy object (Hello), a java. lang. reflect. the invocationhandler interface decouples our proxy object from the proxy object.

Related Article

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.