1, the purpose of dynamic agents
The dynamic proxy is used for separating the code, separating the common code from the various business modules, eliminating the need to implement it in every business module, which reduces the development workload and facilitates maintenance;
eg: "Eat", "talk" both businesses need to use the "mouth" "Shut up" the two lines of code, but after the mouth and shut up before the things are not the same, so that the business module and the general module (that is, mouth, shut up), each time in the speech or meal, the use of common modules + business modules Realize the two things of eating and speaking;
2. Application of dynamic Agent
The most typical application is the implementation of AOP (aspect-oriented programming) in the spring framework based on dynamic agent technology. Aspect-oriented programming, through the slicing code layer, to achieve the separation of business code and common code, so that each business module can share a common code. The approximate principle is as follows: The tangent layer Code provides an interface to invoke other methods (named Invoke), and after passing parameters such as classes and methods through the reflection mechanism , the method is executed in invoke, and the incoming method is only part of the Invoke method. The other part is the generic code, which compiles the common code and the business code together. (In fact, the enhancement in sping is the case)
3. The principle and realization of dynamic agent
Java provides two dynamic proxy methods, one is the JDK dynamic agent, the other is Cglib dynamic agent, the JDK dynamic agent only implements the agent for the interface, Cglib implements the agent of the object, the Chlib is better than the overall performance;
(1) JDK dynamic agent
The JDK dynamic agent is implemented based on "Invocationhandler interface" and "proxy class", and its technical basis is the reflection mechanism in Java and the rewriting in object-oriented.
Java Dynamic Agent