Author: Unknown Source: Unknown Add Time: 2005-2-28 Moonlight software station Aspect Oriented Programming (AOP), aspect-oriented programming, is a hot topic. The purpose of AOP is the purpose of extracting the sections of the business process, which faces a step or phase in the process of processing to obtain a low coupling between the portions during logic. For example, our most common is the log record, give an example, we now provide a service to query student information, but we want to record who is in this query. If we implement the traditional OOP implementation, then we implemented a service interface (StudentInfoservice) and its implementation class (StudentInfoserviceImpl.java), and at the same time we are implementing the class (StudentInfoserviceImpl.java) In order to add the process of implementing its record. In this case, if the service we want to achieve is there? Then add these recording procedures at each implementation class. If this is done, it will be a bit cumbersome, and each implementation class is tightly coupled to the behavior of the log service log, which violates the object-oriented rules. So how can I separate the behavior of the record service from the business process? It seems that it is to query the students' service yourself, but the logging behind these behaviors is recorded, but the student's service does not know that there are these records, which is what we want to discuss the purpose of AOP. AOP programming, it seems to bring us in a part of the function to isolate it, which reduces coupling between a batch of objects, which can be programmed on a function. Let's start from the code. To implement the above goals, we can use a dynamic proxy class (Proxy), complete by intercepting an object's behavior and adds the features we need. Java.lang.Reflect.Proxy class and java.lang.reflect.invocationHandler interface provide a scheme for us to implement dynamic proxy classes, but the object is targeted to some interfaces; if the purpose is class CGLIB provides us with another implementation. The difference between the two will be explained. First, the implementation of interfaces: 1) First, the preparation of our service 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 currently entered is:" Name);}} 2) Now we need a log function, execute and record their behavior before the FindInfo behavior, then we will First, you must intercept the behavior. During the actual implementation process, use a proxy class for us.
Java provides us with a program of dynamic agent classes: 1 'Handling interceptor (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 method, Object [] args) throws Throwable {Object result = null {// Please insert the code here, call log.info before the method ("call log log method" method.getname ()); result = method.invoke (proxy, args); // Original method // Please insert code here, then call} catCH (Exception E) {E.PrintStackTrace ();} Return Result;}} 2 'We implement a factory, in order to facilitate our use of 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 ();} CA tch (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 factory we are all implemented, now test (ClientTest.java):
public class ClientTest {public static void main (String [] args) {StudentInfoService studentInfo = (StudentInfoService) AOPFactory.getAOPProxyedObject ( "StudentInfoServiceImpl"); studentInfo.findInfo ( "punk");}} The output (see your log4j setup) : [Info] Call the log log method FindInfo The name you current is: A Fei, the effect we need, the business handles yourself, but we realize the log function, but business processing (studentinfoservice) does not know if there is Behavior. However, the implementation of the dynamic agent classes provided in Java is a class that implements certain interfaces. If the interface is not implemented, the agent class cannot be created, and the above part: Return Proxy.NewProxyInstance (Obj.getClass (). GetClassLoader (), Obj.getClass (). getInterfaces (), this); did you see it? Obj.getClass (). getInterfaces () requires some interfaces. The following provides an implementation scheme without an interface: Second, a subclass implementation scheme. First, please go to the CGLIB package, http://sourceforge.net/project/showfiles.php? Group_id = 56933. Set the ClassPath path, the implementation of the CGLIB and the Java standard library is different, CGLIB is primarily based on the implementation class (such as StudentInfoserviceImpl.java) to extend a subclass.
Compared to Proxy and InvocationHandler in Dynamic Proxy, net.sf.cglib.proxy.enhancer and MethodInterceptor are responsible for completing the proxy object creation and method intercept processing in CGLIB, generating a subclass of the target class rather than through an interface Interception, enhancer is mainly used to construct dynamic agent subclasses to implement interception, MethodInterceptor (extended Callback interface) is mainly used to implement Around Advice (Concept in AOP): 1) Our business processing (studentinfoserviceImpl.java): public Class StudentInfoserviceImpl {public void FindInfo (String Name) {system.out.println ("The name you currently entered is:" name);}} 2) Implement a tool to process 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 (); public Object getInstrumentedClass (Class clz) {enhancer.setSuperclass (clz); enhancer.setCallback (this); return enhancer .create ();} public object} public object} (Object O, Method Method, Object [] args, methodproxy proxy) Throws throwab Le {log.info ("call log method" method.getname ()); object result = proxy.invokeursuper (o, args); returnursuper;}} 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 ( "punk");}} and output The same is the same.