In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
How to realize from dynamic agent to Spring AOP? for this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
The editor mainly talks about two ways to implement Spring Aop dynamic agent.
1. Spring AOP
Spring is a lightweight container, and the core concepts of Spring are IoC and AOP. It can be seen that AOP is one of the cores of the Spring framework, plays a very important role in the application, and is also the basis of other components of Spring. AOP (Aspect Oriented Programming), that is, aspect-oriented programming, can be said to be a complement to OOP (Object Oriented Programming, object-oriented programming). OOP introduces the concepts of encapsulation, inheritance and polymorphism to establish an object hierarchy, which is used to simulate a collection of common behaviors. However, OOP allows developers to define vertical relationships, but it is not suitable for defining horizontal relationships, such as logging capabilities.
The basic knowledge of AOP is not the focus of this article. We mainly look at the underlying implementation mechanism of the core function of AOP: the implementation principle of dynamic proxy. The interception function of AOP is realized by the dynamic agent in java. Add aspect logic to the target class to generate an enhanced target class (either before or after the target class function is executed, or when the target class function throws an exception. Different cut-in times correspond to different types of Interceptor, such as BeforeAdviseInterceptor,AfterAdviseInterceptor and ThrowsAdviseInterceptor.
So how does a dynamic proxy weave facet logic (advise) into target class methods? Let's introduce and implement two dynamic proxies used in AOP in detail.
Two kinds of dynamic proxies are used in the source code of AOP to achieve the intercept cut-in function: jdk dynamic proxy and cglib dynamic proxy. The two methods exist at the same time, each has its own advantages and disadvantages. Jdk dynamic proxy is implemented by the reflection mechanism within java, while the bottom layer of cglib dynamic proxy is realized by asm. Generally speaking, the reflection mechanism is more efficient in the process of generating classes, while asm is more efficient in the related execution process after generating classes (we can solve the problem of inefficiency in the process of generating classes in asm by caching the classes generated by asm).
Let's take an example to implement these two methods.
2. JDK dynamic Agent 2.1 defines the interface and implementation classes public interface OrderService {public void save (UUID orderId, String name); public void update (UUID orderId, String name); public String getByName (String name);}
The above code defines an interface to the intercepted object, that is, crosscutting concerns. The following code implements the intercepted object interface.
Public class OrderServiceImpl implements OrderService {private String user = null; public OrderServiceImpl () {} public OrderServiceImpl (String user) {this.setUser (user);} /... @ Override public void save (UUID orderId, String name) {System.out.println ("call save () method, save:" + name) } @ Override public void update (UUID orderId, String name) {System.out.println ("call update () method");} @ Override public String getByName (String name) {System.out.println ("call getByName () method"); return "aoho";}} 2.2 JDK dynamic proxy class public class JDKProxy implements InvocationHandler {/ / target object private Object targetObject to be proxied Public Object createProxyInstance (Object targetObject) {this.targetObject = targetObject; return Proxy.newProxyInstance (this.targetObject.getClass (). GetClassLoader (), this.targetObject.getClass (). GetInterfaces (), this);} @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {/ / proxied object OrderServiceImpl bean = (OrderServiceImpl) this.targetObject; Object result = null / / aspect logic (advise), here System.out.println ("- before invoke----"); if (bean.getUser ()! = null) {result = method.invoke (targetObject, args);} System.out.println ("--after invoke----"); return result;} / /.}
The above code implements the dynamic proxy class JDKProxy, implements the InvocationHandler interface, and implements the invoke method in the interface. When the client calls the business method of the proxy object, the proxy object executes the invoke method, and the invoke method delegates the call to targetObject, which is equivalent to calling the method of the target object, judging the authority before the invoke method is delegated, and realizing the interception of the method.
2.3 Test public class AOPTest {public static void main (String [] args) {JDKProxy factory = new JDKProxy (); / / Proxy dynamically creates a proxy instance that conforms to a certain interface for the InvocationHandler implementation class OrderService orderService = (OrderService) factory.createProxyInstance (new OrderServiceImpl ("aoho")); / / orderService the agent executor orderService.save (UUID.randomUUID (), "aoho") from the dynamically generated proxy object }}
The results are as follows:
-before invoke----call save () method, save:aoho---after invoke----3. CGLIB bytecode generates 3.1 classes to proxy
CGLIB can generate proxies for both classes of an interface and classes. In the example, the proxy for the class is implemented.
Public class OrderManager {private String user = null; public OrderManager () {} public OrderManager (String user) {this.setUser (user);} /. Public void save (UUID orderId, String name) {System.out.println ("call save () method, save:" + name);} public void update (UUID orderId, String name) {System.out.println ("call update () method");} public String getByName (String name) {System.out.println ("call getByName () method"); return "aoho";}}
The implementation of this class is the same as the above interface implementation, in order to maintain unity.
3.2 CGLIB dynamic proxy class public class CGLibProxy implements MethodInterceptor {/ / CGLib target object private Object targetObject; public Object createProxyObject (Object obj) {this.targetObject = obj; Enhancer enhancer = new Enhancer (); enhancer.setSuperclass (obj.getClass ()) / / the parameter of the callback method is the proxy class object CglibProxy. Finally, the enhanced target class calls the intercept method enhancer.setCallback (this) in the proxy class object CglibProxy; / / the enhanced target class Object proxyObj = enhancer.create (); / / returns the proxy object return proxyObj } @ Override public Object intercept (Object proxy, Method method, Object [] args, MethodProxy methodProxy) throws Throwable {Object obj = null; / / aspect logic (advise), here System.out.println ("--before intercept----") before the target class code is executed; obj = method.invoke (targetObject, args) System.out.println ("--after intercept----"); return obj;}}
The above implements the methods of creating subclasses and proxies. The getProxy (SuperClass.class) method creates a proxy object by extending the class of the parent class by entering the bytecode of the parent class. The intercept () method intercepts all calls to target class methods, obj represents the instance of the target class, method is the reflection object of the target class method, args is the dynamic input parameter of the method, and methodProxy is the proxy class instance. Method.invoke (targetObject, args) invokes methods in the parent class through the proxy class.
Test public class AOPTest {public static void main (String [] args) {OrderManager order = (OrderManager) new CGLibProxy () .createProxyObject (new OrderManager ("aoho")); order.save (UUID.randomUUID (), "aoho");}
The results are as follows:
-before intercept----call save () method, save:aoho---after intercept----4. Summary
This paper mainly talks about two ways to realize Spring Aop dynamic agent, and introduces their advantages and disadvantages respectively. The premise of the application of jdk dynamic agent is that the target class is based on a unified interface. Without this premise, jdk dynamic proxies cannot be applied. It can be seen that jdk dynamic agent has some limitations. Cglib, a third-party class library, is more widely used and has more advantages in efficiency.
JDK dynamic proxy mechanism is a delegated mechanism, which does not need a third-party library. As long as it needs a JDK environment, it can act as a proxy and dynamically implement the interface class. In the dynamically generated implementation class, it is delegated to hanlder to call the original implementation class method. CGLib must rely on the class library of CGLib, use the inheritance mechanism, and inherit the relationship between the proxy class and the proxy class, so the proxy class can be assigned to the proxied class, and if the proxied class has an interface, the proxy class can also be assigned to the interface.
This is the end of the answer to the question about how to realize the dynamic agent to Spring AOP. I hope the above content can be of some help to you. If you still have a lot of doubts to solve, you can follow the industry information channel to learn more about it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.