What is AOP (Aspect Oriented Programming)
AOP is a programming paradigm that provides the ability to consider program structures from another perspective to improve Object-Oriented Programming (OOP ).
AOP provides a mechanism for developers to describe the cross-concern, and can automatically route the cross-concern to the object-oriented software system, thus realizing the modularization of the Cross-concern.
AOP can encapsulate the logic or responsibilities that are unrelated to the business but called by the business module, such as transaction processing, log management, and permission control, this helps reduce system code duplication, reduce coupling between modules, and facilitate future operability and maintainability.
What can AOP do? It is also a benefit of AOP.
1. Reduce the Coupling Degree of modules
2: Make the system easy to expand
3: late binding of design decisions: with AOP, designers can postpone the decision for future needs, because it
This requirement can be easily implemented as an independent aspect.
4: better code reusability
There are still problems:
You will find that the files to be modified are scattered in many files. If there are many files to be modified, the modification volume will be large, which will undoubtedly increase the chance of errors, it also increases the difficulty of system maintenance.
In addition, if the requirement for adding a function is raised only later in software development, a large number of existing files will not comply with the basic "Open-Close principle ".
Improved Solution
It is implemented in the decorator mode or agent mode.
Decorator mode definition
Dynamically add some additional responsibilities to an object. As for the added function, the decorator mode is more flexible than generating sub-classes.
Proxy mode definition
Provides a proxy for other objects to control access to this object.
JDK dynamic proxy solution (more common solution)
Java code:
View copies to clipboard and print
Public class MyInvocationHandler implements InvocationHandler {
Private Object target;
Public MyInvocationHandler (Object target ){
This.tar get = target;
}
Public Object invoke (Object proxy, Method method, Object [] args)
Throws Throwable {
// 1. record logs 2. Start time statistics 3. Security Check
Object retVal = method. invoke (target, args );
// 4. End of time statistics
Return retVal;
}
Public Object proxy (){
Return Proxy. newProxyInstance (target. getClass (). getClassLoader (),
Target. getClass (). getInterfaces (), new MyInvocationHandler (target ));
}
}
CGLIB dynamic proxy solution:
Java code:
View copies to clipboard and print
Public class MyInterceptor implements MethodInterceptor {
Private Object target;
Public MyInterceptor (Object target ){
This.tar get = target;
}
Public Object intercept (Object proxy, Method method, Object [] args,
MethodProxy invocation) throws Throwable {
// 1. record logs 2. Start time statistics 3. Security Check
Object retVal = invocation. invoke (target, args );
// 4. End of time statistics
Return retVal;
}
Public Object proxy (){
Return Enhancer. create (target. getClass (), new MyInterceptor (target ));
}
}
Features of JDK dynamic proxy
No proxy class, only proxy Interface
CGLIB dynamic proxy features
Proxy class and interface, cannot proxy final class
Essence of dynamic proxy
It is used to enhance the target object and is eventually represented as a class. It is just a dynamic subclass creation without manual subclass generation.
Dynamic proxy restrictions
You can only enhance the function before or after the parent class method is called. You cannot modify the function in the middle. To enhance the function in the method call, ASM (a Java bytecode operation and Analysis Framework)
Better solution-providing AOP
It is recognized that traditional programs often show behaviors that cannot naturally be used across multiple program modules, such as logging and context-sensitive error handling, people call this behavior "CrossCuttingConcern" because it spans the typical responsibility boundaries in a given programming model.
If you have used code that is closely focused, you will know the problems caused by the lack of attention. Because the implementation of cross-cutting behavior is scattered, Developers find that such behavior is difficult to make logical thinking, implementation and change. Therefore, Aspect-Oriented Programming AOP came into being.
Let's look at the concept of AOP again.
Focus
Is the public function of interest, such as transaction management, is a concern. Indicates "what to do"
Join point (Joinpoint ):
During program execution, a specific point is usually added with the focus function, such as when a method is called or when an exception is handled. In Spring AOP, a connection point always represents the execution of a method. Indicates "where to do"
Notification (Advice ):
The action performed on a specific connection point (Joinpoint) of the slice.
There are various types of notifications, including "around", "before", and "after. The notification type will be discussed later. Many AOP frameworks, including Spring, use interceptor as the notification model and maintain a connection point-centric interceptor chain. Indicates "How to do it"
Aspect/Aspect (Aspect ):
Modularization of a focus, which may cross multiple objects. It indicates "where, what to do, and how to do it"
Pointcut ):
The assertion that matches the connection point. A notification is associated with an entry expression and runs on the connection point that meets the entry expression (for example, when a method with a specific name is executed ). How the entry point expression matches the connection point is the core of AOP: Spring uses the AspectJ entry point syntax by default.
Target Object ):
The object notified by one or more sections. Someone also calls it an advised object. Since Spring AOP is implemented through runtime, this object is always a proxied object.
AOP Proxy ):
The AOP framework uses an object created in proxy mode to insert a notification (that is, an application plane) at the connection point, that is, to apply a plane to the target object through proxy. In Spring, the AOP proxy can be implemented using JDK dynamic proxy or CGLIB proxy, and the Application Section is applied through the interceptor model. Note: The schema-based style and @ AspectJ annotation style statement introduced by Spring are transparent to users who use these styles.
Weaving ):
Connect a plane to another application type or object and create a notification object. That is to say, weaving is a process of applying the aspect to the target object to create the AOP proxy object. These can be completed at compilation (for example, using the AspectJ compiler), class loading and runtime. Like other pure Java AOP frameworks, Spring completes weaving at runtime.
Introduction (Introduction ):
It is also called the internal type declaration (inter-type declaration ). Declare additional methods or fields of a type for existing classes. Spring allows the introduction of new interfaces (and a corresponding implementation) to any proxy object. For example, you can use an introduction to implement the IsModified interface of bean to simplify the cache mechanism.
Before advice ):
A notification executed before a connection point, but this notification cannot be executed before the connection point (unless it throws an exception ).
Notification After return (After returning advice ):
Notifications executed after a connection point is completed normally: for example, a method does not throw any exception and returns normally.
Notification After an exception is thrown (After throwing advice ):
The notification that is executed when the method throws an exception and exits.
After notification (finally) advice ):
The notification that is executed when a connection point exits (whether it is normal return or abnormal exit ).
Surround notification (Around Advice ):
Notifications that enclose a connection point, such as method calls. This is the most powerful notification type. Surround notifications can complete custom actions before and after method calls. It will also choose whether to continue executing the connection point or directly return their own return values or throw an exception to end the execution.
Build Environment is the same as above
Define an interface as follows:
Java code:
View copies to clipboard and print
Package cn. ipvs. Spring3.aop;
Public interface Api {
Public String testAop ();
}
Write a class to implement this interface
Java code:
View copies to clipboard and print
Public class Impl implements Api {
Public String testAop (){
System. out. println ("test aop ");
Return "aop is OK ";
}
}
Write a class as the Advice of Before without any special requirements. It is a common class.
Java code:
View copies to clipboard and print
Public class MyBefore {
Public void b1 (){
System. out. println ("now befoer ---------> ");
}
}
In the configuration file, ensure that the namespace aop must be defined during configuration, as follows:
Java code:
View copies to clipboard and print
<? Xml version = "1.0" encoding = "UTF-8"?>
<Beans xmlns = "http://www.springframework.org/schema/beans"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xmlns: context = "http://www.springframework.org/schema/context"
Xmlns: aop = "http://www.springframework.org/schema/aop"
Xmlns: tx = "http://www.springframework.org/schema/tx"
Xsi: schemaLocation ="
Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
<Bean id = "testAopApi" class = "cn. S. spring3.aop. Impl"> </bean>
<Bean id = "myBefore" class = "cn. S. spring3.aop. MyBefore"> </bean>
<Aop: config>
<Aop: aspect id = "abcd" ref = "myBefore">
<Aop: pointcut id = "myPointcut"
Expression = "execution (* cn. S. spring3.aop. *. * (...)"/>
<Aop: before
Pointcut-ref = "myPointcut"
Method = "b1"/>
</Aop: aspect>
</Aop: config>
</Beans>
The client is as follows:
Java code:
View copies to clipboard and print
Public class Client {
Public static void main (String [] args ){
ApplicationContext context = new ClassPathXmlApplicationContext (
New String [] {"applicationContext. xml "});
Api api = (Api) context. getBean ("testAopApi ");
String s = api. testAop ();
System. out. println ("s =" + s );
}
}
The test results are as follows:
Now befoer --------->
Test aop
S = aop is OK
Author: jinnianshilongnian