In Java EE applications, AOP is often used to handle system-level services, such as transaction management, security checks, caching, object pool management, and so on. the basic concept of 1.AOP
AOP considers the process of program from the point of view of program operation, and extracts the slice of the business process. AOP is about the steps in a program's operation and wants to combine the steps of a business process in a better way.
AOP frameworks are not coupled with specific code, and AOP frameworks can handle specific pointcuts (Pointcut) in a program without being coupled to a specific class of concrete classes.
The AOP framework has two features as follows:
☞ Good isolation between the steps
☞ Source code Independence
Here are some terms for cutting-plane programming:
☞ Section (AspectJ): A specific step in a business process, that is, the focus of the application run process, and the focus may be crosscutting multiple objects, so often referred to as crosscutting concerns.
☞ Connection Point (Joinpoint): A specific point in the execution of a program, such as a call to a method, or an exception thrown. In Spring AOP, a connection point is always a call to a method
☞ Enhanced Processing (Advice): The enhanced processing that an AOP framework performs at a specific pointcut. The processing has "around", "before" and "after" type
☞ pointcut (Pointcut): A connection point in which enhanced processing can be inserted. In short, when a connection point satisfies a specified requirement, the connection point is added to the enhanced processing, which becomes the pointcut. Spring defaults to using ASPECTJ pointcut syntax
☞ Introduction: Adds a method or field to the class being processed. Spring allows the introduction of new interfaces to any object being processed. For example, you can use an introduction that enables any object to implement the IsModified interface to simplify caching
☞ target object: an object that is enhanced by an AOP framework, also known as an enhanced object
☞AOP Agent : The object created by the AOP framework, simply put, the proxy is the strengthening of the target object. The AOP agent in spring can be either a JDK dynamic proxy or a cglib proxy
☞ Weaving (weaving): the process of adding enhanced processing to the target object and creating an enhanced object (AOP proxy) is weaving. There are two implementations of weaving: compile-time enhancements such as ASPECTJ, and run-time enhancements such as Cglib. Spring, like other pure Java AOP frameworks, completes weaving at run time.
As you know from the previous introduction, an AOP agent is actually an object that is dynamically generated by the AOP framework and can be used as a target object. The AOP agent contains all the methods of the target object, but the methods in the AOP proxy differ from the methods of the target object: The AOP method adds enhanced processing to a particular pointcut and recalls the method 2.Spring AOP support for the target object
The AOP proxy in spring is generated, managed by spring's IOC container, and its dependencies are managed by the IOC container. Thus, AOP proxies can target other bean instances in the container directly, which can be provided by dependency injection of the IOC container. Spring uses the Java dynamic Proxy to create an AOP proxy by default, so that you can create an agent for any interface instance.
Spring can also use the Cglib proxy, and spring automatically switches to use the Cglib proxy when a proxy class is needed instead of a proxy interface.
Spring currently supports only the method call as a connection point (Joinpoint), and you can consider using ASPECTJ if you want access and update to field as a connection point for enhanced processing.
Throughout AOP programming, there are only three parts that require programmers to participate:
☞ Define common business components
☞ defines pointcuts, a pointcut that may traverse multiple business components
☞ defines enhanced processing, which is the processing action that is woven into an AOP framework for common business components 3. Based on annotation "0 Configuration" mode
To enable spring's support for the @aspectj slice configuration and to ensure that the target bean in the spring container is automatically enhanced by one or more slices, you must configure the following fragment in the Spring configuration file:
<?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:mvc= "Http://www.springframework.org/schema/mvc "
xmlns:context=" Http://www.springframework.org/schema/context "
xmlns:aop=" http:// WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "
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 ">
<!--start AspectJ support-->
<aop:aspectj-autoproxy/>
</beans>
If you do not intend to use spring's XML Schema configuration, you should add the following fragment in the spring configuration file to enable @aspectj support.
<!--start AspectJ support-->
<bean class= " Org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator "/>
to start @aspectj support in a spring application, you also need to add two ASPECTJ libraries to the application's class load path: Aspectjweaver.jar and Aspectjrt.jar ① definition Slice
When @aspectj support is started, as soon as we configure a bean,spring with @aspect annotations in the spring container, the bean is automatically recognized and processed as a slice.
Using @aspect to annotate a Java class, the Java class will act as a slice bean, as shown in the following code fragment.
@Aspect public
class Logaspect {
//define additional content for this class
}
Slice classes (classes decorated with @aspect) can have methods, property definitions, as well as other classes, and may include pointcuts, enhanced processing definitions.
When we use @aspect to decorate a Java class, spring will not treat the bean as a component bean, so the processing bean that is responsible for automatic enhancement will skip over the bean without any enhanced processing of the bean. ② definition before Zengqiang processing
When we use @before to annotate a method in a slice class, the method is treated as a before enhancement. When using @before annotations, you typically specify a value property that specifies a pointcut expression that specifies which pointcuts the enhanced processing will be woven into. For example:
@Component @Aspect public class Beforeadvicetest {//matching all classes under Org.crazyit.app.service.impl package
method is executed as a pointcut @Before ("Execution (* org.crazyit.app.service.impl.*.* (..))")
public void Authority () {SYSTEM.OUT.PRINTLN ("Simulate Execute permission check"); }
}
<?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:mvc=" http:// Www.springframework.org/schema/mvc "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:aop=" Http://www.springframework.org/schema/aop "xsi:schemalocation=" Http://www.springframework.org/schema/beans htt
P://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 "> <!--automatic search component--> <context:compon Ent-scan base-package= "Main.java.service.impl,main.java.aspect"/> <!--boot AspectJ support--> <aop:aspectj-au Toproxy/> </beans>
Note: Need to add Aopalliance.jar ③ definition afterreturning Enhanced processing
Similar to using @before annotations to annotate before enhanced processing, @afterreturning is used to mark a afterreturning enhancement process, and afterreturning enhanced processing will be woven after the target method is properly completed
The following two common properties can be specified when using @afterreturning annotations:
☞pointcut/value: The two properties work the same way, and they are all used to specify the entry expression for the pointcut. When the value of the Pointcut property is specified, the Value property is overwritten
☞returning: Specifies a return value parameter name, which enhances the processing definition by using the parameter name to access the return value of the target method
@Component
@Aspect Public
class Afterreturningadvicetest {
@AfterReturning (returning = "RVT", Pointcut = " Execution (* main.java.service.*.* (..)) ")
public void log (object rvt) {
System.out.println (Get target method return value: + rvt);
SYSTEM.OUT.PRINTLN ("Simulate logging function ...");
}
As seen in the previous program, when using @afterreturning in a program, a returning property is specified, which is RVT, which indicates that a formal parameter named RVT is allowed to be used in the enhanced processing method (log method), which represents the return value of the target method. ④ definition afterthrowing Enhanced processing
The @afterthrowing annotation can be used to annotate a afterthrowing enhanced processing, and afterthrowing enhanced processing is primarily used to handle unhandled exceptions in the program.
When using @afterthrowing, you can specify the following two common properties:
☞pointcut/value: The two properties work the same way, and they are all used to specify the entry expression for the pointcut. When the value of the Pointcut property is specified, the Value property is overwritten
☞returning: Specifies a return value parameter name that enhances the processing definition by using the parameter name to access the exception object thrown in the target method
@Component
@Aspect Public
class Afterthrowingadvicetest {
@AfterThrowing (throwing = "Ex", Pointcut = " Execution (* main.java.service.*.* (..)) ")
public void Dorecoveryactions (Throwable ex) {
System.out.println ("exception thrown in the target method:" + ex);
SYSTEM.OUT.PRINTLN ("enhanced processing after impersonation throws an exception ...");
}
As you can see in the previous program, when you use @AfterThrowing in your program, you specify a throwing property, which is ex, which allows you to use a formal parameter named ex in the enhanced processing method that represents the exception thrown by the target method
@Component public
class Chinese implements person {
@Override public
string SayHello (string name) {
try {
System.out.println ("SayHello method begins to be executed ...");
New Java.io.FileInputStream ("A.txt");
} catch (Exception ex) {
System.out.println (Exception handling for Target class + ex.getmessage ());
}
Return name + "Hello, Spring AOP";
}
public void Eat (String food) {
int a = 5/0;
System.out.println ("I'm Eating:" + food);
}
The SayHello () and eat () two methods in the above program throw an exception, but the exception in the SayHello () method will be captured by the method, so spring AOP does not handle the exception, and eat () Method throws a Airthmeticexception exception that is not handled by any program, so spring AOP handles the exception.
Impersonation Execute permission Check ... the SayHello method begins to be executed ... Exception handling A.txt of the target class (the system cannot find the specified file.)
Gets the target method return value: Qiuxiao Hello, spring AOP analog logging capabilities ... Qiuxiao Hello, spring AOP impersonation Execute permission check ...
Exception thrown in target method: Java.lang.ArithmeticException:/by zero simulates enhanced processing after throwing an exception ... Exception in thread ' main ' java.lang.ArithmeticException:/by zero at Main.java.service.impl.Chinese.eat (Chinese.java : At Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native method) at Sun.reflect.NativeMethodAccessorImpl.invoke (Unknown source) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown source) at Java.lang.reflect.Method.in Voke (Unknown Source) at Org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection (aoputils.java:309 ) at Org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint ( reflectivemethodinvocation.java:183) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:150) at Org.springframework.aop.framework.adapter.MethodBeforeAdviceINterceptor.invoke (METHODBEFOREADVICEINTERCEPTOR.JAVA:50) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (reflectivemethodinvocation.java:172) at Org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke (aspectjafterthrowingadvice.java:55) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (reflectivemethodinvocation.java:172) at Org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke ( AFTERRETURNINGADVICEINTERCEPTOR.JAVA:50) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (reflectivemethodinvocation.java:172) at Org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke ( exposeinvocationinterceptor.java:89) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:172) at Org.springframework.aop.framework.JdkDynamicAopProxy.invoke ( jdkdynamicaopproxy.java:202) at Com.sun.proxy. $Proxy 8.eat (Unknown SOurce) at Main.test.Test.main (test.java:13)
Note: Using the Throwing property also has an additional effect: it can be used to qualify the pointcut to match only the specified type of exception-the type of the ex parameter defined in the Dorecoveryactions () method above is NullPointerException, The pointcut only matches the case where the NullPointerException exception is thrown. The ex-parameter type of the Dorecoveryactions () method above is Throwable, indicating that the pointcut can match any exception thrown
AOP's afterthrowing processing can handle exceptions to the target method, but this is not the same as using catch captures directly: catch capture means that the exception is completely handled, and if a new exception is not thrown again in a catch block, the method can end gracefully While afterthrowing handles the exception, but it cannot fully handle the exception, and the exception is still propagated to the previous level of caller ⑤after enhanced processing
Spring also provides an after-enhanced processing that is somewhat similar to afterreturning enhancement processing, but also differs:
☞afterreturning Enhanced processing will not be woven until the target method is successfully completed
☞after enhanced processing, regardless of how the target method is constrained (including both successful completion and unexpected abort), will be woven into
Because no matter how a method ends, after enhanced processing is woven, after-enhanced processing must be prepared to handle both normal returns and exception returns, which is typically used to release resources.
When using @after, you need to specify a value property that specifies the pointcut to which the enhanced processing is woven
@Component
@Aspect Public
class Afteradvicetest {
@After (value = "Execution (* main.java.service.*.* (..))") Public
void Release () {
System.out.println ("Free resources after simulating method ...");
}
⑥around Enhanced Processing
@Around used to annotate around enhanced processing, around Zengqiang processing is a powerful enhancement that approximates the sum of before and afterreturning enhanced processing, which can be woven into the enhanced action before the target method is executed. You can also weave the enhanced action after the target method is executed.
Unlike before, afterreturning enhanced processing, around enhanced processing can even determine when the target method executes, executes, or even completely blocks the execution of the target method.
Around enhanced processing can change the value of the parameter that executes the target method, or it can change the return value after the target method is executed.
Around enhanced processing is powerful, but usually requires a thread-safe environment. If you need to share some state data before and after the target method executes, you should consider using around enhancement processing, especially if you need to use enhanced processing to block the execution of the target, or if you need to change the target method return value, you can only use around enhancement.
You need to specify a value property when you use @around, which specifies the pointcut from which the enhanced processing is woven.
When defining a around enhancement processing method, the first parameter of the method must be a Proceedingjoinpoint type (containing at least one formal parameter), and the Proceedingjoinpoint proceed () should be invoked in the enhanced processing method body. method to execute the target method-this is the key to around enhanced processing to fully control how the target method executes and how it is executed, and if the program does not invoke the Proceedingjoinpoint proceed () method, the target method is not executed.
When you call the Proceedingjoinpoint proceed () method, you can also pass in a object[] object in which the value in the array is passed as an argument to execute the method.
@Component
@Aspect Public
class Aroundadvicetest {
@Around (value = "Execution (* main.java.service.*.* (..))") Public
Object Processtx (proceedingjoinpoint JP) throws Throwable {
System.out.println ("Before executing the target method, simulate starting things ...") ;
Executes the target method and saves the return value
object rvt = Jp.proceed (new string[] {changed parameter}) after the target method is executed;
System.out.println ("After the execution of the target method, simulate the end of things ...");
return RVT + "new content";
}
Before executing the target method, simulate the beginning of things ...
Impersonation Execute permission Check ... the SayHello method begins to be executed ... Exception handling A.txt of the target class (the system cannot find the specified file.)
After the target method is executed, simulate the end of things ...
Get Target method return value: Changed parameter Hello, Spring AOP new content analog logging feature ...
To release resources after the simulation method is finished ...
Changed parameters Hello, Spring AOP new content to execute target method before simulating start things ...
Impersonation Execution Permission Check ...
I'm eating: Changed parameters The exception thrown in the target method: Java.lang.ArithmeticException:/By zero simulates the enhanced processing after throwing an exception ...
To release resources after the simulation method is finished ... Exception in thread ' main ' java.lang.ArithmeticException:/by zero at Main.java.service.impl.Chinese.eat (Chinese.java :) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native method) at Sun.reflect.NativeMethodAccessorImpl.invoke (Unknown source) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown source) at Java.lang.reflect.Method.in Voke (Unknown Source) at Org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection (aoputils.java:309 ) at Org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint ( reflectivemethodinvocation.java:183) at Org.springframework.aop.framework.ReflectiveMethodInvocation.procEed (reflectivemethodinvocation.java:150) at Org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke ( METHODBEFOREADVICEINTERCEPTOR.JAVA:50) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:172) at Org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed ( methodinvocationproceedingjoinpoint.java:91) at Main.java.aspect.AroundAdviceTest.processTx ( Aroundadvicetest.java:16 in Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native method) at Sun.reflect.NativeMeth Odaccessorimpl.invoke (Unknown source) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown source) at JAVA.L Ang.reflect.Method.invoke (Unknown Source) at Org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs ( abstractaspectjadvice.java:621) at Org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod ( abstractaspectjadvice.java:610) at ORG.SPRINGFRAmework.aop.aspectj.AspectJAroundAdvice.invoke (aspectjaroundadvice.java:65) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (reflectivemethodinvocation.java:172) at Org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke (aspectjafterthrowingadvice.java:55) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (reflectivemethodinvocation.java:172) at Org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke ( AFTERRETURNINGADVICEINTERCEPTOR.JAVA:50) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (reflectivemethodinvocation.java:172) at Org.springframework.aop.aspectj.AspectJAfterAdvice.invoke ( aspectjafteradvice.java:42) at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:172) at Org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke ( exposeinvocationinterceptor.java:89) at Org.springframework. Aop.framework.ReflectiveMethodInvocation.proceed (reflectivemethodinvocation.java:172) at Org.springframework.aop.framework.JdkDynamicAopProxy.invoke (jdkdynamicaopproxy.java:202) at com.sun.proxy.$ Proxy10.eat (Unknown Source) at Main.test.Test.main (test.java:13)
When the Proceedingjoinpoint proceed () method is invoked, the passed-in object[] parameter value is used as an argument to the target method, if the length of the incoming object[array is not equal to the number of parameters required by the target method, or object[] The array element does not match the type of the parameter required by the target method, and the program will receive an exception.
In order to obtain the number and type of parameters of the target method, an enhanced processing method is required to access the parameters of the method of executing the target.