When it comes to AOP, you will definitely think of spring because this thing is too powerful. But you must be clear that AOP is a programming idea, and Spring is just an implementation of AOP.
First, Baidu:
In the software industry, AOP is the abbreviation of Aspect Oriented Programming, which means: a technology that implements unified maintenance of program functions through precompilation methods and dynamic agents during runtime. AOP is a continuation of OOP, a hot topic in software development, an important part of Spring framework, and a derivative paradigm of functional programming. The various parts of the business logic can be isolated by using AOP, thereby reducing the coupling between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development.
Today, let’s use Java native proxy to implement simple AOP functions.
First, you need to know basic reflection knowledge, otherwise you may feel confused.
No more words, just start typing
First, let’s write a simple interface. The name is AnimalInterface, which is used to declare some basic methods to regulate animals.
These methods include setting names, obtaining names, callings, and attributes (forgive me for not being educated, in fact, it is to obtain whether it is terrestrial or aquatic or amphibious)
package proxy.imp;public interface AnimalInterface { //Set the name void setName(String name); //Get the name String getName(); //Call void says(); //Get the permanent void getProperty();}Then we implement this interface and create a Dog named Xiao Hei
package proxy;import proxy.imp.AnimalInterface;public class DogImp implements AnimalInterface { private String name = "Xiaohei"; public DogImp() { } @Override public void setName(String name) { this.name = name; } @Override public String getName() { return this.name; } @Override public void says() { System.out.println("Puppy: wool wool wool......"); } @Override public void getProperty() { System.out.println("Puppy is a land animal, but can swim"); }} Everyone must be impatient to realize AOP-like functions...
Let's first create a class called AOPHandle to implement the InvocationHandler interface. When you cannot use invoke, proxy as reflection parameter, because the interface of the proxy object is different from an object, this proxy mechanism is interface-oriented rather than class-oriented. If you use proxy, it will cause infinite recursion. Then there is stack overflow, but it can still reflect successfully once. This shows that the proxy object and the proxy of the object are different. However, we can obtain the class object through proxy.getClass() of the proxy parameter, and then obtain the methods and parameters of the proxy class. This also provides an implementation method for annotation injection, specific method injection, and attribute injection. Let's talk about this later.
package proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class AOPHandle implements InvocationHandler{ //Save object private Object o; public AOPHandle(Object o) { this.o=o; } /** * This method will be called automatically, Java dynamic proxy mechanism* will be passed in the following parameter* @param Object proxy The interface of the proxy object, different from the object* @param Method method called method* @param Object[] args method parameters* When you cannot use invoke, proxy as reflection parameter, because the interface of the proxy object is different from object*. This proxy mechanism is interface-oriented, not class-oriented **/ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //Method return value Object ret=null; //Print method name System.err.println("Execution method:"+method.getName()+"n parameter type is:"); //Print parameter for(Class type: method.getParameterTypes()) System.err.println(type.getName()); //Print return type System.err.println("Return data type:"+method.getReturnType().getName()); //Reflection call method ret=method.invoke(o, args); //Declare the end System.err.println("Method execution end"); //Return the return value of the reflective call method return ret; }}The dynamic proxy has been completed...and then our AnimalFactory...and let's continue
package proxy;import java.lang.reflect.Proxy;public class AnimalFactory { /*** * Get object method* @param obj * @return */ private static Object getAnimalBase(Object obj){ //Get proxy object return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new AOPHandle(obj)); } /*** * Get object method* @param obj * @return */ @SuppressWarnings("unchecked") public static T getAnimal(Object obj){ return (T) getAnimalBase(obj); } /*** * Get object method* @param className * @return */ @SuppressWarnings("unchecked") public static T getAnimal(String className){ Object obj=null; try { obj= getAnimalBase(Class.forName(className).newInstance()); } catch (Exception e) { e.printStackTrace(); } return (T)obj; } /*** * Get object method* @param clz * @return */ @SuppressWarnings("unchecked") public static T getAnimal(Class clz){ Object obj=null; try { obj= getAnimalBase(clz.newInstance()); } catch (Exception e) { e.printStackTrace(); } return (T)obj; }} Finally it's the end...what's missing? Come here to see the effect...
Haha... waiter, I'll serve...oh~No, it's a test category...haha///
package proxy;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;import proxy.AnimalFactory;import proxy.imp.AnimalInterface;@RunWith(BlockJUnit4ClassRunner.class)public class AOPTest { @Test public void Test1() { AnimalInterface dog=AnimalFactory.getAnimal(DogImp.class); dog.say(); System.out.println("My name is "+dog.getName()); dog.setName("Ergouzi"); System.out.println("My name is "+dog.getName()); }} What? What, in the end, this is useful, isn't this a trick? Just capture this thing, what's the use...
What kind of AOP, why don’t I see any AOP, how can I enter the custom method? Just a syso input, and fool the audience into this?….
OK, then let's go ahead and see how to implement the injected custom method...
First, add an interface, let's call it AOP injection interface. Name it AOPMethod
Create after and before methods, receive Object proxy, Method method, Object[] args parameters
This will do more things... For example, before executing the method, record the class status, write the log. Monitor the xx variable,,,
Open your brain.
package proxy.imp;import java.lang.reflect.Method;public interface AOPMethod{ //Method executed before the instance method is executed void after(Object proxy, Method method, Object[] args); //Method executed after the instance method is executed void before(Object proxy, Method method, Object[] args);} Then modify the AOPHandle class and add the AOPMethod property.
Modify the constructor method to obtain an AOPMethod instance when class initialization.
Finally modify the invoke method.... Go to the code directly
package proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import proxy.imp.AOPMethod;public class AOPHandle implements InvocationHandler{ //Save object private AOPMethod method; private Object o; public AOPHandle(Object o,AOPMethod method) { this.o=o; this.method=method; } /** * This method will be called automatically, Java dynamic proxy mechanism* The following parameter will be passed in * @param Object proxy The interface of the proxy object is different from the object* @param Method method called method* @param Object[] args method parameters* When invoke cannot be used when proxy is used as a reflection parameter, because the interface of the proxy object is different from object* This proxy mechanism is interface-oriented, not class-oriented**/ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object ret=null; //The modification place is here this.method.before(proxy, method, args); ret=method.invoke(o, args); //The modification place is here this.method.after(proxy, method, args); return return; }} Huhu, the task is done, it seems that everything is a problem, cute...
Update the test class immediately...
package proxy;import java.lang.reflect.Method;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;import proxy.imp.AOPMethod;import proxy.imp.AnimalInterface;@RunWith(BlockJUnit4ClassRunner.class)public class AOPTest { public static void main(String[] args) { AnimalInterface dog = AnimalFactory.getAnimal(DogImp.class, new AOPMethod() { // Here is the AOP cutting method before method execution public void before(Object proxy, Method method, Object[] args) { System.err.println("I'm in" + method.getName() + "Execute before method execution"); } // Here is the AOP cutting method after method execution public void after(Object proxy, Method method, Object[] args) { System.err.println("I'm in" + method.getName() + "Execute after method execution"); } }); dog.say(); String name1="My name is" + dog.getName(); System.out.println(name1); dog.setName("Ergouzi"); String name2="My name is"+dog.getName(); System.out.println(name2); }} Huhu, dear, do you feel like injecting? Do you feel like you have cut your own method into it??? Haha…
It seems that everything is perfect, but I always feel that something is missing? Oh, yes, there is a lack of configuration files like Spring.
In fact, those are already very simple. Let's leave them to you. Just design the XML format and wait, what do you say? You can't intercept custom methods?
Can't intercept custom methods like Spring? Oh~~NO, in fact, you can use the method and methodName to make a judgment in before(Object proxy, Method method, Object[] args) to use the method and give methodName.
Of course, this example has no practical significance, and it cannot be compared with various perfect AOP frameworks. This article only provides you with a way of thinking, but you must remember that no matter how awesome the things are, they are accumulated bit by bit
Example download: http://xiazai.VeVB.COM/201701/yuanma/JavaAOP_jb51.rar
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.