This is the 26th day of my participation in the August Text Challenge.More challenges in August

The interceptor

  • Before I introduce interceptors, let’s warm up with a bit of code
public interface HiService {
    public void sayHi(String name);
}
Copy the code
  • Serive implementation layer
public class HiServiceImpl implements HiService {
    @Override
    public void sayHi(String name) {
        if (null == name || name.trim() == "") {
            System.out.println("Name is null!");
        }
        System.out.println("Hi! " + name);
        
    }
}
Copy the code
  • Above is a simple service and its implementation layer
  • Let’s implement an interceptor interface
Public Interceptor {public Boolean before(); Public void after(); public Object around(Invocation invocation) { throw InvocationTargetException,IllegalAccessException; } public void afterReturning(); Public void afterThrowing(); // Public void afterThrowing(); Boolean useAround(); }Copy the code
  • Check the source Invocation below the Reflect package
  • The most important thing in itpublic Object proceed()This method uses reflection to call the original method
  • Is the use of theinvoke()function

ProxyBean

  • Proxy classes are used to weave service classes and interception methods into corresponding flows
  • When you want to give a primary school 🍬, it must be approved by the parents, the parents can deal with some things for the child, some things the parents can also help the child to refuse 🙅🏻♀️
  • From the above examples, we can see that parents are the primary school students’ proxy, just like our real estate agent, which can help us do a lot of things
  • The real object was the pupil

  • The one on the left is for 🍬 people, the parents in the middle, and the pupils on the right

  • To implement proxybeans, we need to implement the InvocationHandler interface
  • The InvocationHandler, on the other hand, has a method invoke, and the implementation ideas can include two broad categories
    • 1. Bind the proxy object, save the interceptor/proxy object/Object being Approached in it
    • 2. Handle method logic for proxy objects
    • Includes parameters and exception handling for the proxy object and the current method run
    • In fact, in the use of the framework, the framework has helped us to do a good job