Programming Aspect Oriented Programming (AOP), aspect-oriented programming, is a very popular topic. The main purpose of AOP is to extract the section in the process of business processing, which is faced with a step or a stage in the process of processing, to obtain the isolation effect of the low coupling between the parts of the logic process. For example, our most common is the log record, for example, we now provide a service to query student information, but we want to record who made this query. If we follow the traditional OOP implementations, we implement a service interface (Studentinfoservice) and its implementation class (Studentinfoserviceimpl.java) that query student information, and in order to record, we are implementing classes ( Studentinfoserviceimpl.java), the procedure in which to add its implementation record. In this case, what if we have to implement more than one service? It is necessary to add these logging procedures to each implemented class. This is a bit cumbersome, and each implementation class is tightly coupled to the behavior of the logging service log, violating object-oriented rules. So how to separate the behavior of recording service from the process of business processing? It looks as if the student's service is in progress, but the underlying log records the behavior, but querying the student's service is not aware of the documented process, which is what we want to discuss about AOP. AOP programming, as if we are in a certain aspect of the function to be isolated from a group of objects, so that with a group of objects to reduce the coupling, you can program a function.
Let's start with the code, and to achieve these goals, we can use a dynamic proxy class (proxy) to do this by intercepting the behavior of an object and adding the functionality we need. The Java.lang.reflect.Proxy class and the Java.lang.reflect.InvocationHandler interface in Java provide a scheme for us to implement the dynamic proxy class, but the object of the scheme is to implement some interfaces, if the target is class, Cglib Provides us with another implementation scenario. The difference between the two will be explained.
First, the implementation of the interface 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 ("The name you are currently typing is:" +name);
}
}
2 Now we need a log function that executes and records its behavior before findinfo behavior, so we first intercept the behavior. In the actual execution of the process with a proxy class to do for us. Java provides us with a scenario for implementing a dynamic proxy class:
1 ' class for 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 Invoke (Object Proxy,method method,object[] args) throws throwable{
Object Result=null;
try{
Please insert the code here to call before the method
Log.info ("Call log Log Method" +method.getname ());
Result=method.invoke (Proxyobj,args); Original method
Insert your code here, and then call the
}catch (Exception e) {
E.printstacktrace ();
}
return result;
}
}
2 ' We implement a factory, in order to facilitate our use of this interceptor 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 basic interception and its plant we have achieved, now testing (Clienttest.java):
public class clienttest{
public static void Main (string[] args) {
Studentinfoservice studentinfo= (Studentinfoservice) aopfactory.getaopproxyedobject ("StudentInfoServiceImpl");
Studentinfo.findinfo ("Teddy Boy");
}
}
Output results (see your log4j settings):
[INFO] Call log log method Findinfo
Your current name is: Punk.
So the effect we need comes out, the business processes itself, but we implement the logging function, and the business process (Studentinfoservice) has no idea of the behavior at all. But the implementation of the dynamic proxy class provided in Java is for the class that implements some interfaces, and if the interface is not implemented, the proxy class cannot be created, look at the above section:
Return Proxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), this);
Do you see it? Obj.getclass (). Getinterfaces () requires the implementation of some interfaces. The following are the implementation scenarios that do not implement the interface:
Second, the implementation of the sub-class scheme.
First of all, please surf the Internet cglib bag, http://sourceforge.net/project/showfiles.php?group_id=56933. With the classpath path set, Cglib differs from the implementation scenario provided by the Java Standard Library, Cglib is primarily implemented by extending a subclass based on an implementation class such as Studentinfoserviceimpl.java. Corresponds to the proxy and Invocationhandler in dynamic proxy, Net.sf.cglib.proxy.Enhancer and Methodinterceptor are responsible for the completion of proxy object creation and method interception in Cglib, resulting in a subclass of the target class rather than an interface to implement method interception. Enhancer is primarily used to construct dynamic proxy subclasses to implement interception, Methodinterceptor (extended callback interface) is primarily used to implement around advice (concepts in AOP):
1 Our Business process (Studentinfoserviceimpl.java):
public class studentinfoserviceimpl{
public void Findinfo (String name) {
System.out.println ("The name you are currently typing is:" +name);
}
}
2 Implement a tool to process the log function (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 enhancer=new enhancer ();
}
3) Let's Test It (Aoptest.java):
public class aoptest{
public static void Main (string[] args) {
Aopinstrumenter instrumenter=new Aopinstrumenter ();
Studentinfoserviceimpl studentinfo= (Studentinfoserviceimpl) Instrumenter.getinstrumentedclass ( Studentinfoserviceimpl.class);
Studentinfo.findinfo ("Teddy Boy");
}
}
The output results are the same as above.
Cglib in order to achieve the above purposes, the main provision of the class
1) enhancer:setcallback (Callback), Setsuperclass (Class), create () returns the dynamic subclass object
2 The interface that Methodinterceptor must implement: Intercept (Object,method,object[],methodproxy) Returns the result of the original method invocation. Same as the principle of proxy.
Three or more of the two simple AOP solutions are ready for you, you can write your own test, the following is a brief introduction to the basic concept of AOP:
1) aspect (CUT): the implementation of the Cross-cutting function, is for the section of the module. The most common is the logging module, so that the program is divided into several tiers by function, if the traditional inheritance, the business model to inherit the log module does not make any sense, and by creating a logging slice can use AOP to achieve the same functionality.
2 Jointpoint (Connection point): The connection point is where the slice is inserted into the application, the point can be called by the method, and it is thrown unexpectedly. A connection point is where an application provides a way to insert a slice, and you can add new methods. For example, our pointcut can be considered a findinfo (String) method.
3 Advice (processing logic): Advice is the implementation of our cutting function, it notifies the program of new behavior. As in logging, logging advice includes the logging implementation code, such as writing logs to a file. Advice is inserted into the application at Jointpoint. Above we have implemented the function of advice in Myhandler.java
4) Pointcut (tangent): Pointcut can control which advice you apply to jointpoint, and usually you use pointcuts to match explicit names and patterns with regular expressions. decided that the Jointpoint would be notified.
5) Introduction: Allows new methods and properties to be added to the class.
(6) Target (target Class): Refers to those who will use the advice class, generally refers to the independent of those business models. such as the above Studentinfoserviceimpl.
7 Proxy (proxy class): The proxy mode is used. Refers to an object that has advice applied, and 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
We have a simple introduction to AOP programming so far, I hope this article is helpful to you readers, on this blog have any suggestions can leave a message to me: gdanthrowwy@126.com
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.