In Java EE applications, some system-level services, such as transaction management, security checks, caching, object pool management, and so on, are often handled through AOP. Basic concepts of 1.AOP
AOP takes the process of the program from the point of view of the program and extracts the facets of the business process. AOP is all about the steps in a program's run, and it's a better way to combine the steps of a business process.
The AOP framework is not coupled with specific code, and the AOP framework can handle specific pointcuts (Pointcut) in a program without coupling to specific specific classes.
The AOP framework has the following two characteristics:
good isolation between each step of the
Source code Independence
Here are some terms for tangent-oriented programming:
AspectJ: A specific step in the operation of a business process, that is, the focus of the application's running process, where the focus may be crosscutting multiple objects, so often referred to as crosscutting concerns.
connection Point (Joinpoint): A definite point in the execution of a program, such as a call to a method, or an exception thrown. In Spring AOP, the connection point is always called by the method
Enhanced processing (Advice): An AOP framework performs enhanced processing at a particular pointcut. Handles types such as "Around", "before", and "after"
Pointcut: You can insert a connection point for enhanced processing. In a nutshell, when a connection point satisfies a specified requirement, the connection point is added with enhanced processing, which becomes a pointcut. Spring uses ASPECTJ pointcut syntax by default
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 simplify caching by using an introduction that enables any object to implement the IsModified interface.
target object: an object that is enhanced by the AOP framework, also known as an enhanced object
☞AOP Agent : The object created by the AOP framework, simply put, the agent is the enhancement of the target object. The AOP proxy in spring can be either a JDK dynamic agent or a cglib proxy
Weaving: the process of adding enhanced processing to a target object and creating an enhanced object (an AOP proxy) is to weave it in. There are two implementations of weaving: compile-time enhancements (such as ASPECTJ) and runtime enhancements (such as Cglib). Spring, like other pure Java AOP frameworks, completes weaving at run time.
It is known from the previous introduction that an AOP proxy is actually an object that is dynamically generated by the AOP framework, which can be used as a target object. The AOP proxy 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 callbacks the target object's method 2.Spring AOP Support
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 the target, which can be provided by the dependency injection of the IOC container. Spring uses the Java dynamic Proxy to create an AOP proxy by default, so that you can create proxies for any interface instances.
Spring can also use the Cglib proxy, which automatically switches to use the Cglib proxy when a proxy class is required instead of a proxy interface.
Spring currently supports only method calls as Connection points (Joinpoint), and if you need to add access and updates to the field as a connection point for enhanced processing, you might consider using ASPECTJ.
Throughout AOP programming, there are only three parts that require programmer involvement:
Define common business components
Define Pointcuts, a pointcut may cross over multiple business components
Enhanced processing is defined as the processing action that the AOP framework weaves into ordinary business components 3. Annotation-based "0 configuration" approach
In order to enable spring support for @aspectj facets configuration and to ensure that the target bean in the spring container is automatically enhanced by one or more facets, the following fragment must be configured 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 launch @aspectj support in a spring app, you also need to add two ASPECTJ libraries to your app's class load path: Aspectjweaver.jar and Aspectjrt.jar ① defining Facets
When @aspectj support is enabled, as long as we configure a bean,spring with a @aspect annotation in the spring container, the bean is automatically recognized and processed as a slice.
Using @aspect to label a Java class, the Java class will be used as a slice bean, as shown in the following code fragment.
@Aspect public
class Logaspect {
//define other contents of this class
}
Slice classes (classes decorated with @aspect) can have methods, property definitions as well as other classes, and may contain pointcuts and enhanced processing definitions.
When we use @aspect to decorate a Java class, spring will not treat the bean as a component bean, so the post-processing bean responsible for auto-enhancement will skip over the bean and will not make any enhancements to the bean. ② defining before safeguarded processing
When we use @before to annotate a method in a slice class, the method is treated as before enhancement. When using @before annotations, you typically need to specify a value property that specifies a pointcut expression that specifies which pointcuts the enhancement will be woven into. For example:
@Component @Aspect public class Beforeadvicetest {//matches all of the classes under Org.crazyit.app.service.impl package
Execution of the method as a pointcut @Before ("Execution (* org.crazyit.app.service.impl.*.* (..))")
public void Authority () {System.out.println ("Impersonation execution 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 "> <!--Auto-search components--<context:compon Ent-scan base-package= "Main.java.service.impl,main.java.aspect"/> <!--start AspectJ Support--<aop:aspectj-au Toproxy/> </beans>
Note: You need to add Aopalliance.jar ③ to define afterreturning enhanced processing
Similar to using @before annotations to annotate before enhancement processing, use @afterreturning to annotate a afterreturning enhancement process, 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 are the same, they are used to specify the cut-in expression corresponding to the pointcut. When the value of the Pointcut property is specified, the Value property values are overwritten
☞returning: Specifies a return value parameter name that is used by the method that enhances the processing definition to access the return value of the target method through the parameter name
@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 ("Analog logging Function ...");}
}
As you can see in the program above, when using @afterreturning in your program, you specify a returning property with RVT, which indicates that a formal parameter named RVT is allowed in the enhanced processing method (log method) that represents the return value of the target method. ④ defining afterthrowing enhancement processing
Using @afterthrowing annotations can be used to annotate a afterthrowing enhancement process, 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 are the same, they are used to specify the cut-in expression corresponding to the pointcut. When the value of the Pointcut property is specified, the Value property values are overwritten
☞returning: Specifies a return value parameter name that enhances the method of processing definition to access the exception object thrown in the target method through the parameter name
@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 seen in the program above, when @AfterThrowing is used in the program, a throwing property is specified, which is ex, which allows the use of a formal parameter named ex in an 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 started 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 will throw an exception, but the exception in the SayHello () method will be captured by the method, so spring AOP does not handle the exception; eat () The Airthmeticexception method throws an exception, and the exception is not handled by any program, so spring AOP handles the exception.
Impersonation execution Permission Check ... the SayHello method begins to be executed ... Exception handling for the target class A.txt (the system cannot find the file specified.)
Gets the target method return value: Qiuxiao Hello, Spring AOP simulation logging feature ... Qiuxiao hello, spring AOP impersonation Execute permission check ...
Exception thrown in the target method: Java.lang.ArithmeticException:/By zero to simulate the 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 has an additional effect: it can be used to qualify pointcuts to match only exceptions of the specified type--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, which indicates that the pointcut matches the case of throwing any exception
Although the afterthrowing processing of AOP can handle exceptions to the target method, this processing differs from the direct use of catch snaps: catch snapping means that the exception is fully handled, and the method can end gracefully if no new exception is thrown in the catch block While afterthrowing processing handled the exception, it could not handle the exception completely, and the exception would still propagate to the previous caller ⑤after enhanced processing
Spring also provides a after-enhancement process, which is somewhat similar to afterreturning enhancement, 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 exception aborts), will be woven into
Because no matter how the method ends, after enhancement processing is woven, so after enhancement processing must be prepared to handle both normal return and exception return, which is typically used to release resources.
When using @after, you need to specify a value property that specifies the entry point that the enhanced processing is woven into
@Component
@Aspect Public
class Afteradvicetest {
@After (value = "Execution (* main.java.service.*.* (..))") Public
void Release () {
System.out.println ("Frees resources after simulation method ends ...");}
}
⑥around Enhanced Processing
@Around for labeling around enhanced processing, around safeguarded processing is a powerful enhancement that approximates the sum of before and afterreturning enhancements, and around enhanced processing can be used to weave the enhancement action before the target method is executed. You can also weave the enhancement action after the target method is executed.
Unlike before, afterreturning enhanced processing, around enhanced processing can even determine when the target method is executed, how it is executed, and even the execution of the target method can be completely blocked.
Around enhanced processing can change the parameter values of the execution target method, or it can change the return value after the execution of the target method.
Around enhanced processing is powerful, but it 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 to enhance processing, especially if you need to use enhanced processing to block the execution of the target, or if you need to change the return value of the target method, you can only use around enhancement.
When using @around, you need to specify a value property that specifies the pointcut into 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), in the body of the enhanced processing method, call Proceedingjoinpoint's proceed () Method executes the target method-this is the key to around enhanced processing that can fully control the timing and execution of the target method, and the target method will not be executed if the program does not call Proceedingjoinpoint's proceed () method.
When you call Proceedingjoinpoint's proceed () method, you can also pass in a object[] object, and the value in the array is passed to the target method as an argument to the execution method.
@Component
@Aspect Public
class Aroundadvicetest {
@Around (value = "Execution (* main.java.service.*.* (..))") Public
Object Processtx (proceedingjoinpoint JP) throws Throwable {
System.out.println ("simulate starting things before executing the target method ...") ;
Executes the target method and saves the return value after the target method executes
object rvt = Jp.proceed (new string[] {"changed parameter"});
SYSTEM.OUT.PRINTLN ("After executing the target method, simulating the end of things ...");
Return RVT + "What's new";
}
}
Simulate starting things before executing the target method ...
Impersonation execution Permission Check ... the SayHello method begins to be executed ... Exception handling for the target class A.txt (the system cannot find the file specified.)
After executing the target method, simulate the end of things ...
Get the target method return value: The changed parameter Hello, Spring AOP new content simulation logging function ...
Releasing resources after the simulation method ends ...
The changed parameters Hello, Spring AOP new content to execute the target method before the simulation begins the thing ...
Impersonation Execution Permission Check ...
I'm eating: The exception that is thrown in the parameter target method that is changed: java.lang.ArithmeticException:/By zero to simulate the enhanced processing after throwing an exception ...
Releasing resources after the simulation method ends ... 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) at 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 calling Proceedingjoinpoint's proceed () method, the passed-in object[] parameter value will be used as the parameter of the target method, if the incoming object[] array length is not equal to the number of parameters required by the target method, or object[] The program will have an exception if the array element does not match the type of the parameter required by the target method.
In order to get the number and type of parameters of the target method, it is necessary to enhance the processing method to access the parameters of the execution target method.