Aop
AOP (Aspect oriented programming), which is aspect-oriented programming, can be said to complement and refine OOP (object oriented programming, OO programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy that simulates a collection of public behavior. However, OOP allows developers to define vertical relationships, but it is not appropriate to define landscape-like relationships, such as logging capabilities. The log code tends to spread horizontally across all object hierarchies, and it has nothing to do with the core functionality of the object it corresponds to, such as the persistence of other types of code, such as security, exception handling, and transparency, the extraneous code scattered around is called crosscutting (cross Cutting), in the OOP design, It leads to a lot of duplication of code and is not conducive to the reuse of individual modules.
AOP technology, on the contrary, uses a technique called "crosscutting" that splits the encapsulated object interior and encapsulates public behavior that affects multiple classes into a reusable module, named "Aspect", or tangent. The so-called "cut-off", simply said to be those unrelated to the business, but for the business module calls together the logic or responsibility to encapsulate, easy to reduce the system duplication of code, reduce the coupling between modules, and conducive to future operability and maintainability.
Using "crosscutting" techniques, AOP divides software systems into two parts: core concerns and crosscutting concerns . The main process of business process is the core concern, and the part that has little relation is the crosscutting concern. One feature of crosscutting concerns is that they often occur in many of the core concerns and are similar everywhere, such as authority authentication, logging, and things. The role of AOP is to separate the various concerns in the system, separating the core concerns from the crosscutting concerns.
AOP Core Concepts
1. Cross-cutting concerns
What methods to intercept and how to deal with them, these concerns are called crosscutting concerns.
2. Slice (aspect)
A class is an abstraction of an object's characteristics, and a facet is an abstraction of a crosscutting concern.
3, Connection point (Joinpoint)
The point that is intercepted, because spring only supports connection points of the method type, so the connection point in spring refers to the method being intercepted, in fact the connection point can also be a field or a constructor
4. Entry point (pointcut)
Definition of interception of connection points
5. Notice (advice)
The so-called notification refers to the interception to the connection point after the code to execute, the notification is divided into pre-, post-, exception, final, surround notification five categories
6. Target Object
Target object for the agent
7. Weave in (weave)
The process of applying a slice to the target object and causing the proxy object to be created
8. Introduction (Introduction)
Without modifying the code, the introduction can dynamically add some methods or fields to the class at run time
Spring's support for AOP
The AOP agent in spring is generated and managed by the spring IOC container, and its dependencies are managed by the IOC container . Therefore, the AOP proxy can use the other bean instances in the container directly as a target, a relationship that can be provided by the dependency injection of the IOC container. The rules for creating a proxy for spring are:
1, the default use of Java Dynamic Agent to create an AOP proxy (with the interface is preferred), so that you can create a proxy for any interface instance
2, when the class that needs the agent is not the proxy interface, spring switches to use the Cglib proxy, the principle is the target object to inherit the proxy , you can also force the use of Cglib
AOP programming is actually a simple thing, and throughout AOP programming, programmers only need to participate in three parts:
1. Define Common business components
2, define pointcuts, a pointcut may cross-cutting multiple business components
3, the definition of enhanced processing, enhanced processing is the AOP framework for ordinary business components to weave the processing action
So the key to AOP programming is defining pointcuts and defining enhanced processing, and once the appropriate pointcuts and enhancements are defined, the AOP framework automatically generates an AOP proxy, the method of the Proxy object = The method of enhancing processing + the Proxied object .
Implementing Dynamic Proxies:
Package Service; Public Interface userservice { void Save (); void Delete (); void update (); void find ();}
PackageService; Public classUserserviceimplImplementsUserService {@Override Public voidSave () {System.out.println ("Save the user!"); } @Override Public voidDelete () {System.out.println ("Delete User!"); } @Override Public voidUpdate () {SYSTEM.OUT.PRINTLN ("Update user!"); } @Override Public voidfind () {System.out.println ("Find a user!"); }}
Packageproxy;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;Importservice. UserService;Importservice. Userserviceimpl;//Dynamic Agent Public classUserserviceproxyfactoryImplementsInvocationhandler { PublicUserserviceproxyfactory (userservice us) {Super(); This. US =us; } Privateuserservice us; PublicUserService Getuserserviceproxy () {//Generating Dynamic AgentsUserService usproxy = (userservice) proxy.newproxyinstance (userserviceproxyfactory.class. getClassLoader (), Userserviceimpl.class. Getinterfaces (), This); //return returnUsproxy; } @Override PublicObject Invoke (Object Arg0, Method method, object[] arg2)throwsthrowable {System.out.println ("Open the transaction!"); Object Invoke=Method.invoke (US, arg2); System.out.println ("Commit the transaction!"); returninvoke; }}
Packageproxy;Importorg.junit.Test;Importservice. UserService;Importservice. Userserviceimpl; Public classDemo {@Test//Dynamic Agent Public voidfun1 () {userservice US=NewUserserviceimpl (); Userserviceproxyfactory Factory=Newuserserviceproxyfactory (US); UserService Usproxy=Factory.getuserserviceproxy (); Usproxy.save (); //The proxy object implements the same interface as the Proxied object//the proxy object has no inheritance relationship to the Proxied objectSystem.out.println (UsproxyinstanceofUSERSERVICEIMPL);//false }}
Implement CGLIB agent:
Packageproxy;ImportJava.lang.reflect.Method;ImportOrg.springframework.cglib.proxy.Enhancer;ImportOrg.springframework.cglib.proxy.MethodInterceptor;ImportOrg.springframework.cglib.proxy.MethodProxy;Importservice. UserService;Importservice. Userserviceimpl;//Cglib Agent Public classUserServiceProxyFactory2ImplementsMethodinterceptor { PublicUserService Getuserserviceproxy () {enhancer en=NewEnhancer ();//Build Proxy ObjectEn.setsuperclass (Userserviceimpl.class);//set who to delegate toEn.setcallback ( This); UserService US= (UserService) en.create ();//Create a proxy object returnus; } @Override PublicObject Intercept (Object Prxoyobj, method, object[] arg, Methodproxy methodproxy)throwsThrowable {//Open TransactionSYSTEM.OUT.PRINTLN ("Open transaction!")); //call the original methodObject returnvalue =methodproxy.invokesuper (Prxoyobj, ARG); //Commit a transactionSYSTEM.OUT.PRINTLN ("COMMIT TRANSACTION!")); returnreturnvalue; }}
Packageproxy;Importorg.junit.Test;Importservice. UserService;Importservice. Userserviceimpl; Public classDemo {@Test Public voidfun2 () {UserServiceProxyFactory2 factory=NewUserServiceProxyFactory2 (); UserService Usproxy=Factory.getuserserviceproxy (); Usproxy.save (); //To determine if a proxy object belongs to a Proxied object type//the proxy object inherits the proxy object =>trueSystem.out.println (UsproxyinstanceofUSERSERVICEIMPL);//true }}
Spring Framework Learning Note 4:SPRINGAOP implementation principle