Spring framework study NOTE 4: SpringAOP implementation principle, springspringaop
AOP
AOP (Aspect Oriented Programming) is a supplement and improvement of Object-Oriented Programming (OOP. OOP introduces concepts such as encapsulation, inheritance, and Polymorphism to establish an object hierarchy for simulating a set of public behaviors. However, OOP allows developers to define vertical relationships, but it is not suitable for defining horizontal relationships, such as the log function. Log Code is usually distributed horizontally across all object layers, and its core functions are irrelevant to other types of code, this is also true for security, exception handling, and transparent continuity. Unrelated code distributed everywhere is called cross-cutting. in OOP design, it leads to a lot of code duplication, and is not conducive to the reuse of each module.
The AOP technology is the opposite. It uses a technology called "cross-cutting" to segment the encapsulated object, encapsulate the public behaviors that affect multiple classes into a reusable module and name it "Aspect", that is, the Aspect. The so-called "aspect" is simply encapsulated by the logic or responsibilities that are not related to the business, but are called by the business module, so as to reduce the repeated code of the system and reduce the coupling between modules, it is also conducive to future operability and maintainability.
Using the "cross-cutting" technology, AOP divides the software system into two parts:Core concernsAndCross-concern. The main process of business processing is the core focus, and the part that has little to do with it is the cross-cutting focus. One feature of cross-cutting concerns is that they often occur in multiple aspects of the core concerns, and are similar everywhere, such as permission authentication, logs, and transactions. The function of AOP is to separate the various concerns in the system from the core concerns and the cross-cutting concerns.
Core AOP concepts
1. Cross-cutting concerns
Methods to intercept and how to handle the interception are called cross-cutting concerns.
2. aspect)
Class is the abstraction of object features, and the aspect is the abstraction of cross-cutting concerns.
3. Connection Point (joinpoint)
The intercepted point. Because Spring only supports connection points of the method type, the connection point in Spring refers to the method to be intercepted. In fact, the connection point can also be a field or constructor.
4. pointcut)
Definition of interception of connection points
5. advice)
The notification refers to the code to be executed after the interception to the connection point. The notification is divided into five categories: front, rear, exception, final, and surround notification.
6. Target object
Proxy target object
7. weave)
Process of applying a cut surface to the target object and causing the creation of the proxy object
8. introduction)
Without modifying the code, you canRuntimeDynamically add some methods or fields to the class
Spring's support for AOP
In Spring, the AOP agent is generated and managed by the Spring IOC container, and its dependency is also managed by the IOC container.. Therefore, the AOP proxy can directly use other bean instances in the container as the target. This relationship can be provided by the dependency injection of the IOC container. The rules for creating proxy in Spring are as follows:
1,By default, Java Dynamic proxy is used to create an AOP proxy (with interfaces preferred)In this way, you can create a proxy for any interface instance.
2,When the class to be proxy is not a proxy interface, Spring will switch to use CGLIB proxy. The principle is to inherit the proxy for the target object., You can also use CGLIB forcibly
AOP programming is actually very simple. Throughout AOP programming, programmers only need to participate in three parts:
1. Define Common Business Components
2. Define an entry point. A single entry point may cross multiple business components.
3. Define the enhancement processing. The enhancement processing is the processing action that is woven into common business components in the AOP framework.
Therefore, the key to AOP programming is to define the entry point and definition enhancement processing. Once an appropriate entry point and enhancement processing are defined, the AOP framework will automatically generate the AOP proxy, namely:Proxy object method = enhanced processing + proxy object.
Implement Dynamic Proxy:
package service;public interface UserService { void save(); void delete(); void update(); void find();}
Package service; public class UserServiceImpl implements UserService {@ Override public void save () {System. out. println ("save User! ") ;}@ Override public void delete () {System. out. println (" delete a user! ") ;}@ Override public void update () {System. out. println (" update user! ") ;}@ Override public void find () {System. out. println (" find a user! ");}}
Package proxy; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy; import service. userService; import service. userServiceImpl; // dynamic proxy public class UserServiceProxyFactory implements InvocationHandler {public UserServiceProxyFactory (UserService us) {super (); this. us = us;} private UserService us; public UserService getUserServiceProxy () {// generate a dynamic generation UserService usProxy = (UserService) Proxy. newProxyInstance (UserServiceProxyFactory. class. getClassLoader (), UserServiceImpl. class. getInterfaces (), this); // return usProxy;} @ Override public Object invoke (Object arg0, Method method, Object [] arg2) throws Throwable {System. out. println ("Open the transaction! "); Object invoke = method. invoke (us, arg2); System. out. println (" Commit transaction! "); Return invoke ;}}
Package proxy; import org. junit. test; import service. userService; import service. userServiceImpl; public class Demo {@ Test // dynamic proxy public void fun1 () {UserService us = new UserServiceImpl (); UserServiceProxyFactory factory = new UserServiceProxyFactory (us); UserService usProxy = factory. getUserServiceProxy (); usProxy. save (); // The proxy object and the proxy object implement the same interface // The proxy object and the proxy object do not inherit from the System. out. println (usProxy instanceof UserServiceImpl); // false }}
ImplementationCGLIBProxy:
Package proxy; import java. lang. reflect. method; import org. springframework. cglib. proxy. enhancer; import org. springframework. cglib. proxy. methodInterceptor; import org. springframework. cglib. proxy. methodProxy; import service. userService; import service. userServiceImpl; // cglib proxy public class UserServiceProxyFactory2 implements MethodInterceptor {public UserService getUserServiceProxy () {Enhancer en = new Enh Ancer (); // generate the agent object en. setSuperclass (UserServiceImpl. class); // sets the proxy en for whom. setCallback (this); UserService us = (UserService) en. create (); // create proxy Object return us;} @ Override public Object intercept (Object prxoyobj, Method method, Object [] arg, MethodProxy methodProxy) throws Throwable {// open the transaction System. out. println ("Open the transaction! "); // Call the original method Object returnValue = methodProxy. invokeSuper (prxoyobj, arg); // submit the transaction System. out. println (" Submit the transaction! "); Return returnValue ;}}
Package proxy; import org. junit. test; import service. userService; import service. userServiceImpl; public class Demo {@ Test public void fun2 () {UserServiceProxyFactory2 factory = new UserServiceProxyFactory2 (); UserService usProxy = factory. getUserServiceProxy (); usProxy. save (); // determines whether the proxy object belongs to the proxy object type. // The proxy object inherits the proxy object => true System. out. println (usProxy instanceof UserServiceImpl); // true }}