Introduction to AOP programming-Java

Source: Internet
Author: User
Aspect oriented programming (AOP) is a hot topic for Aspect-Oriented Programming. The main purpose of AOP is to extract the sections in the business processing process. It is faced with a certain step or stage in the processing process, in order to obtain the isolation effect of low coupling between different parts in the logical process. For example, the most common one is logging. For example, we now provide a service to query student information, but we want to record who has performed this query. Based on the traditional OOP implementation, studentinfoservice and studentinfoserviceimpl are implemented. java), and in order to record, we are implementing the class (studentinfoserviceimpl. java. In this case, what if we want to implement multiple services? Add these record processes to each implemented class. In this case, it will be a little complicated, and every implementation class is tightly coupled with the behavior of recording service logs, violating the object-oriented rules. So how can we separate the recorded service behavior from the business processing process? It seems that the Service for querying students is in progress, but the log records are used to record these behaviors. However, the Service for querying students does not know the existence of these record processes, this is where we want to discuss the purpose of AOP. The programming of AOP seems to be to isolate the functions proposed in a certain aspect from a batch of objects. This reduces coupling with a batch of objects and allows programming of a certain function.
Let's start with the Code. To achieve the above goal, we can use a dynamic proxy class to intercept the behavior of an object and add the required functions. Java. lang. reflect. proxy class and Java. lang. reflect. the invocationhandler interface provides a solution for implementing the dynamic proxy class, but the solution implements some interfaces for the objects. If the purpose is a class, cglib provides us with another implementation solution. And so on.
I. Interface Implementation Scheme:
1) first write our business interface (studentinfoservice. Java ):
Public interface studentinfoservice {
Void findinfo (string studentname );
}
And its implementation class (studentinfoserviceimpl. Java ):
Public class studentinfoserviceimpl implements studentinfoservice {
Public void findinfo (string name ){
System. Out. println ("your current name is:" + name );
}
}
2) Now we need a log function to execute and record the findinfo behavior before the findinfo behavior, so we must first intercept this behavior. In the actual execution process, a proxy class is used for us. Java provides a solution for implementing dynamic proxy classes:

1 'class for processing interception purposes (myhandler. Java)
Import org. Apache. log4j. Logger;
Import java. Lang. Reflect. invocationhandler;
Import java. Lang. Reflect. proxy;
Import java. Lang. Reflect. method;

Public class myhandler implements invocationhandler {
Private object proxyobj;
Private Static logger log = logger. getlogger (myhandler. Class );
 
Public object BIND (Object OBJ ){
This. proxyobj = OBJ;
Return proxy. newproxyinstance (obj. getclass (). getclassloader (), obj. getclass (). getinterfaces (), this );
}
 
Public object invoke (Object proxy, method, object [] ARGs) throws throwable {
Object result = NULL;
Try {
// Insert the code here and call it before the Method
Log.info ("call log method" + method. getname ());
Result = method. Invoke (proxyobj, argS); // the original method
// Insert the code here and call the Method
} Catch (exception e ){
E. printstacktrace ();
}
Return result;
}
}
2' we implement a factory. To make it easier for us to use this interception class (aopfactory. Java ):
Public class aopfactory {
Private Static object getclassinstance (string clzname ){
Object OBJ = NULL;
Try {
Class CLS = Class. forname (clzname );
OBJ = (object) CLS. newinstance ();
} Catch (classnotfoundexception cnfe ){
System. Out. println ("classnotfoundexception:" + cnfe. getmessage ());
} Catch (exception e ){
E. printstacktrace ();
}
Return OBJ;
}
 
Public static object getaopproxyedobject (string clzname ){
Object proxy = NULL;
Myhandler handler = new myhandler ();
Object OBJ = getclassinstance (clzname );
If (OBJ! = NULL ){
Proxy = handler. BIND (OBJ );
} Else {
System. Out. println ("can't get the proxyobj ");
// Throw
}
Return proxy;
}
}

3) We have implemented the basic interception and the factory. Now test (clienttest. Java ):
Public class clienttest {
Public static void main (string [] ARGs ){
Studentinfoservice studentinfo = (studentinfoservice) aopfactory. getaopproxyedobject ("studentinfoserviceimpl ");
Studentinfo. findinfo ("A Fei ");
}
}
Output results (depending on your log4j settings ):
[Info] Call the LOG method findinfo
Your current input name is: afei
In this way, the effect we need is achieved, and the business processing is in progress, but we have implemented the log function, and the business processing (studentinfoservice) does not know that this behavior exists. However, the implementation of the dynamic proxy class provided in Java is aimed at the class that implements some interfaces. If the interface is not implemented, the proxy class cannot be created. See the preceding section:
Return proxy. newproxyinstance (obj. getclass (). getclassloader (), obj. getclass (). getinterfaces (), this );
See no? OBJ. getclass (). getinterfaces () requires that some interfaces be implemented. Which of the following implementation schemes do not implement interfaces are provided:

II. Implementation Scheme of sub-classes.
First of all, please go online with cglib package, http://sourceforge.net/project/showfiles.php? Group_id = 56933. After the classpath path is set, cglib is different from the implementation solution provided by the java standard library. cglib is mainly implemented by extending a subclass Based on the implementation class (such as studentinfoserviceimpl. Java. Corresponds to the proxy and invocationhandler in the dynamic proxy, net. SF. cglib. proxy. enhancer and methodinterceptor are responsible for creating proxy objects and intercepting methods in cglib. They generate subclass of the target class instead of implementing method interception through interfaces, enhancer is mainly used to construct dynamic proxy subclass to implement interception. methodinterceptor (Extended callback Interface) is mainly used to implement the concept of AOP und advice (AOP ):
1) Our business processing (studentinfoserviceimpl. Java ):
Public class studentinfoserviceimpl {
Public void findinfo (string name ){
System. Out. println ("your current name is:" + name );
}
}
2) implement a tool to process logs (aopinstrumenter. Java ):
Import net. SF. cglib. Proxy. methodinterceptor;
Import net. SF. cglib. Proxy. enhancer;
Import net. SF. cglib. Proxy. methodproxy;
Import java. Lang. Reflect. method;
Import org. Apache. log4j. Logger;

Public class aopinstrumenter implements methodinterceptor {
Private logger log = logger. getlogger (aopinstrumenter. Class );
Private enhancer = new enhancer ();
 
Public object getinstrumentedclass (class clz ){
Enhancer. setsuperclass (clz );
Enhancer. setcallback (this );
Return enhancer. Create ();
}
 
Public object intercept (Object o, method, object [] ARGs, methodproxy proxy) throws throwable {
Log.info ("call log method" + method. getname ());
Object result = proxy. invokesuper (O, argS );
Return result;
}
 
}
3) Let's test (aoptest. Java ):
Public class aoptest {
Public static void main (string [] ARGs ){
Aopinstrumenter instrumenter = new aopinstrumenter ();
Studentinfoserviceimpl studentinfo = (studentinfoserviceimpl) instrumenter. getinstrumentedclass (studentinfoserviceimpl. Class );
Studentinfo. findinfo ("A Fei ");
}
}
The output result is the same as the preceding one.
Cglib provides classes for the above purpose
1) enhancer: setcallback (callback), setsuperclass (class), create () returns the dynamic subclass object
2) the interface required by methodinterceptor: intercept (object, method, object [], methodproxy) returns the result of the original method call. The principle is the same as that of proxy.

III. The above two simple AOP implementation solutions are all ready for you. You can write and test it yourself. The following briefly introduces the basic concepts of AOP:
1) aspect: implements the cross-cutting function, which is a plane-specific module. The most common is the logging module. In this way, the program is divided into several layers by function. If the program is inherited based on the traditional model, it makes no sense to inherit the log module from the business model, by creating a logging plane, you can use AOP to implement the same functions.
2) jointpoint: the connection point is the place where the slice is inserted into the application. This point can be called by methods and thrown out of an accident. A connection point is the place where the application inserts a plane. You can add a new method. For example, the preceding cut point can be considered as the findinfo (string) method.
3) Advice (processing logic): advice is the implementation of our aspect function, which notifies the program of new behaviors. For example, in logging, logging advice includes the implementation code of logging, such as writing logs to a file. Advice is inserted into the application at jointpoint. We have implemented the advice function in myhandler. java.
4) pointcut: pointcut can control which advice you apply to the jointpoint. Generally, you use pointcuts to apply the explicit names and patterns through regular expressions. It determines that the jointpoint will be notified.
5) Introduction: allows you to add new methods and attributes to the class.
6) Target (target class): refers to the classes that will use advice, and generally refers to the independent business models. For example, studentinfoserviceimpl.

7) proxy: the proxy mode is used. It refers to the object that applies advice. It looks very similar to the target object.
8) Weaving (insert): refers to the process of applying aspects to a target object to create a proxy object: complie time, classload time, Runtime

 

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.