AOP basics
1.1 AOP
1.1.1 Introduction: AOP, what is AOP?
Aspect Oriented programming, through precompilation or runtime dynamic proxy (depending on how to use static AOP, dynamic AOP) to achieve unified maintenance of Program functions a technology. AOP is a continuation of OOP, a hot topic in software development, and an important content in Spring framework. AOP can be used to isolate each part of the business logic, so as to reduce the degree of coupling between each part of the business logic and improve the reusability of the program.
AOP, like OOP, is just a programming paradigm. AOP does not specify how the code that implements the AOP protocol should be implemented. AOP, like OOP, is just a programming idea, and there are two contrasting ways to understand AOP.
1.1.2 Understand AOP in a comparative way — AOP versus OOP
To understand AOP (aspect oriented programming) by understanding OOP (object oriented programming) OOP is a kind of software development idea, which is based on class; AOP is a program maintenance idea, which is based on method. OOP is characterized by inheritance, polymorphism and encapsulation. AOP is characterized by method enhancement (with the shadow of a decorator pattern) and comes in both static and dynamic AOP.
1.1.3 Understand AOP in a comparative way — static AOP versus dynamic AOP
Static AOP: The AOP framework makes changes to the program at compile time, that is, implementing enhancements to the target classes to generate static AOP proxy classes (the generated *.class files have been modified to require the use of a specific compiler). Example: AspectJ. Dynamic AOP: The AOP framework dynamically generates AOP proxies at run time (in memory as JDK dynamic proxies or Cglib AOP proxy classes) to enable enhancements to target objects. Example: Spring AOP.
The following table:
AOP form | For example, | The characteristics of |
---|---|---|
Compile-time weaving (that is, static AOP) | AspectJ | Has good performance, but requires a special compiler |
Runtime weaving (i.e., dynamic AOP) | Spring AOP and JBoss | Poor performance, pure Java code implementation, no special compiler required |
So AOP in Spring is a kind of dynamic AOP that dynamically generates AOP proxies at run time to implement enhancements to target objects.
1.1.4 Understand AOP in a comparative way — Spring IOC vs. Spring AOP
Spring IOC and Spring AOP are both Spring feature points, but there is a connection between the two features. AOP proxies in Spring are generated and managed by Spring’s loC container, and their dependencies are also managed by the loC container. Thus, an AOP proxy can directly target other Bean instances in the container, and this relationship can be provided by dependency injection in the loC container. Spring’s approach to AOP differs from other frameworks in that it does not aim to provide the most complete IMPLEMENTATION of AOP (although Spring AOP has this capability). Instead, Spring focuses on the integration between AOP implementations and Spring LOC containers to help solve common problems in enterprise development. As a result, Spring AOP is typically used in conjunction with the Spring LOC container, and Spring AOP was never intended to compete with aspects by providing a comprehensive AOP solution, Spring AOP uses a proxy-based AOP implementation, while AspectJ uses a compile-time enhanced solution.
1.2 AOP project requirements
Now suppose that there are three pieces of identical code in the system, which are usually completed by “copy” and “paste”. The schematic diagram of software developed by this “copy” and “paste” method is shown in the figure below:
The downside of this approach is that if one day, the dark code in the image above needs to be modified, do you have to open the code in three places? What if, instead of three places, this code is contained in 100 places, or even 1,000 places? To solve this problem, it is common to define the dark part of the code shown in the figure as a method and then call that method in each of the three code segments. In this way, the schematic diagram of the software system is shown as follows:
If need to modify the darker part code, just change a place, no matter how many places in the whole system to invoke the method, the application does not need to modify the place, only need to modify the called method – in this way, greatly reduce the complexity of software maintenance, this is the AOP use in the project development practice.
1.3 AOP related concepts (using Spring AOP to explain AOP related concepts)
AOP meaning (interpretation of AOP meaning based on AOP concepts) : In the idea of section-oriented programming, functions are divided into core business functions and peripheral functions. The so-called core business, such as logging in, adding data, deleting data are called core business; So-called peripheral functions, such as performance statistics, logging, transaction management, etc. Peripheral functions are defined as facets in Spring’s aspect oriented AOP thinking, in which core business functions and aspect functions are developed separately and then “woven” together, a process called AOP.
AOP core Concepts (8 in total)
1. Cross-cutting concern noun, which methods are intercepted and how to deal with them after interception? These concerns are called cross-cutting concerns
2. Aspect classes are abstractions of object features, while aspects are abstractions of crosscutting concerns
The point to which a joinpoint is intercepted. Since Spring only supports joinpoints of method types, the joinpoint refers to the method being intercepted. In fact, joinpoints can also be fields or constructors
A pointcut defines which methods to intercept. It can intercept all methods of a class, or it can intercept only methods of a class that begin with a specific character
Advice refers to the specific implementation code of a cross-cutting concern in a cutting Aspect, that is, the code to be executed after intercepting the join point. There are five types of notification: pre-@before, post-@after, exception @afterthrowing, final @afterRUNNING, and surround-around @notification. It is the code that executes the section at what time After intercepting the method.
Side note: AspectJ supports five types of notification annotations (as illustrated in the following Spring AOP code): @before: pre-notification, @after: post-notification, and @afterRunning After method execution: After the method returns the result, @afterthrowing: the exception notification is executed. After the method throws an exception, @around: the surround notification is executed Around the method
Target noun: the Target object of an agent. Weave verb to apply an aspect to a Target and cause the process of creating a proxy object to be called weave. Introduction can dynamically add methods or fields to a class at run time without modifying the code
Static AOP implementation: AspectJ AOP
2.1 the AspectJ AOP
Why AspectJ? AspectJ is an AOP framework based on the Java language that provides powerful AOP capabilities. Many subsequent AOP frameworks have borrowed or adopted some of these ideas. Since AOP in Spring4.0 is well integrated with aspects, mastering aspects is learning from Spring The foundation of AOP. Since Spring2.0, Spring AOP has already introduced support for AspectJ and allows AOP programming directly with AspectJ, and Spring’s own AOP APIS strive to be AspectJ compliant, so learning Spring AOP necessarily requires learning from aspects At first, because it is the most popular AOP solution in the Java world, you can use aspects directly for AOP programming without using the Spring framework.
AspectJ profile AspectJ is an AOP implementations of the Java language, it mainly includes two parts: one part defines how to express, definition of AOP programming grammar specification, through the grammar, you can easily use AOP to solve the problem of overlapping concerns that exist in the Java language, another part is a tool, include compilers, debugging tools And so on. AspectJ is one of the earliest and most powerful AOP implementations, and has a good implementation of the whole AOP mechanism. Many other AOP implementations also borrow or adopt many designs from AspectJ. In the Java domain, many syntactic structures in aspects have basically become the standard in the AOP domain.
2.2 AspectJ AOP practices
2.2.1 Directory Structure
As shown in figure:
2.2.2 Two entity classes and startup classes
Code:
package mypackage;
/** * Created by 30292 on 2020/2/22. */
public class Test {
public static void main(String[] args){
Hello hello=new Hello();
hello.foo();
hello.addUser("Zhang"."1000");
World world=new World();
world.bar();
}
}
class Hello {
public void foo(){
System.out.println("Execute the foo() method of the Hello component");
}
public int addUser(String name,String pass){
System.out.println("Add a user by executing the Hello component addUser() :"+name);
return 20;
}
}
class World {
public void bar(){
System.out.println("Execute the bar() method of the World component"); }}Copy the code
2.2.3 Three sections
packagemypackage; public aspect AuthAspect{ before():execution(* mypackage.*.*(..) ) { System.out.println("Before simulate permission check..."); } } aspect LogAspect{ after():execution(* mypackage.*.*(..) ) { System.out.println("After simulation logging..."); } } aspect TxAspect{ Object around():call(* mypackage.*.*(..) ){ System.out.println("Around Start simulation to start a transaction...");
Object rvt=proceed();
System.out.println("Around Finish emulates the transaction...");
returnrvt; }}Copy the code
2.2.4 Running Results
The result is as follows (printed in both AspectJ and the actual method) :
Dynamic AOP implementation: Spring AOP
Spring AOP uses a proxy-based AOP implementation, while AspectJ uses a compile-time enhanced solution.
3.1 Spring AOP basic knowledge
3.1.1 Spring IOC Implement Spring AOP
AOP proxies in Spring are generated and managed by Spring’s loC container, and their dependencies are also managed by the loC container. Thus, an AOP proxy can directly target other Bean instances in the container, and this relationship can be provided by dependency injection in the loC container. Spring’s approach to AOP differs from other frameworks in that it does not aim to provide the most complete IMPLEMENTATION of AOP (although Spring AOP has this capability). Instead, Spring focuses on the integration between AOP implementations and Spring LOC containers to help solve common problems in enterprise development. As a result, Spring AOP is typically used in conjunction with the Spring LOC container, and Spring AOP was never intended to compete with aspects by providing a comprehensive AOP solution, Spring AOP uses a proxy-based AOP implementation, while AspectJ uses a compile-time enhanced solution.
Spring AOP Proxy
Spring defaults to using Java dynamic proxies to create AOP proxies, which can be created for any interface instance. Spring can also use the Cglib proxy, automatically switching to the cglib proxy when the proxy class is needed instead of the proxy interface. But Spring recommends interface oriented programming, so business objects typically implement one or more interfaces, and JDK dynamic proxies are used by default, but cglib proxies can also be enforced.
Spring AOP is a dynamic AOP
Spring AOP is dynamic AOP, implemented using pure Java, does not require specific compilation tools, and Spring AOP does not require control of the classloader hierarchy, so it can work well in any Java Web container or application server.
3.1.4 Spring AOP join points
Spring currently only supports method calls as join Points, but AspecJ can be considered if you need access and updates to member variables as join points for enhanced processing.
3.1.5 Spring AOP implementation
Spring2.0 seamlessly integrates Spring AOP,IOC, and AspectJ, allowing all AOP applications to be fully integrated into the Spring-based framework without affecting the Spring AOP API or the AOP Alliance API. Spring AOP maintains downward compatibility that still allows AOP programming to be done directly using the Spring AOP API.
Once you’ve mastered the concepts above, it’s easy to see that AOP programming is actually quite straightforward. There are only three parts of AOP programming that require programmer involvement. (1) Define common business components; (2) Define pointcuts, where a pointcut may crosscut multiple business components; (3) define enhancement processing, which is the processing action woven into the AOP framework for common business components; The first part of this is the most mundane and needs no explanation. The key to AOP programming, then, is to define pointcuts and enhancements. Once the appropriate pointcuts and enhancements are defined, the AOP framework will automatically generate AOP proxies, and the methods of AOP proxies are roughly as follows: We use AspectJ to define pointcuts and enhanced processing. In this way, Spring still has two options for defining pointcuts and enhanced processing: (1) Annotation-based “zero configuration” approach: @aspect, @pointcut and other annotations are used to mark pointcuts and enhancements in 3.2. (2) XML-based configuration file management: Spring configuration files are used to define pointcuts and enhancements in 3.3
Automatic enhancement automatic enhancement means that Spring will determine whether one or more aspects need to be enhanced for the specified Bean and automatically generate the corresponding proxy accordingly, so that the enhancement process can be invoked at the appropriate time. The whole process is transparent to the developer and automatic, so it is automatic enhancement.
3.2 Spring AOP practices: Annotation approach implementation
3.2.1 Directory Structure
3.2.2 Two POJO classes
Let’s start with two POJO classes, which are simple:
package com.pojo;
import org.springframework.stereotype.Component;
/** * Created by 30292 on 2020/2/21. */
@Component("hello")
public class Hello {
public void foo() {
System.out.println("Execute the foo() method of the Hello component");
}
public void addUser(String name, String pass) {
System.out.println(Add a user by executing the Hello component addUser: + name);
}
public void _functionException(int orgin) {
int a = orgin / 0; // The divisor is 0}}Copy the code
package com.pojo;
import org.springframework.stereotype.Component;
/** * Created by 30292 on 2020/2/21. */
@Component("world")
public class World {
public void bar(){
System.out.println("Execute the bar() method of the World component"); }}Copy the code
3.2.3 Five Aspect classes
Look at the five aspect classes, which describe five ways to enhance annotations: @before @after @afterreturning @afterthrowing @around
@Before
package com.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import java.util.Arrays;
@Aspect
public class BeforeAspect { A class with an @aspect annotation becomes a section
@Before("execution(* com.pojo.*.*(..) )")
public void beforeAspectFunction(JoinPoint joinPoint){
System.out.println("Here's Before enhancement.");
System.out.println("Before enhancement: The target method woven into the enhancement processing is:"+joinPoint.getSignature().getName());
System.out.println("Before enhancement: The target method parameter is:"+ Arrays.toString(joinPoint.getArgs()));
System.out.println("Before enhancement: The target object woven into the enhancement processing is:"+joinPoint.getTarget()); }}Copy the code
@After
package com.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import java.util.Arrays;
@Aspect
public class AfterAspect {
@After("execution(* com.pojo.*.*(..) )")
public void afterAspectFunction(JoinPoint joinPoint){
System.out.println("Here's After enhancement.");
System.out.println("After enhancement: The target method woven into the enhancement process is:"+joinPoint.getSignature().getName());
System.out.println("After enhancement: The target method parameter is:"+ Arrays.toString(joinPoint.getArgs()));
System.out.println("After enhancement: The target object woven into the enhancement process is:"+joinPoint.getTarget()); }}Copy the code
@AfterReturning
package com.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import java.util.Arrays;
@Aspect
public class AfterReturningAspect {
@AfterReturning(returning = "rvt", pointcut = "execution(* com.pojo.*.*(..) )")
public void afterReturningAspectFunction(JoinPoint joinPoint, Object rvt){
System.out.println(Here is the AfterReturning enhancement, which prints the target method return value:+rvt);
System.out.println("AfterReturning enhancement: The target method of being woven into enhancement is:"+joinPoint.getSignature().getName());
System.out.println("AfterReturning enhancement: The parameters of the target method are:"+ Arrays.toString(joinPoint.getArgs()));
System.out.println("AfterReturning enhancement: The target object woven into enhancement is:"+joinPoint.getTarget()); }}Copy the code
@AfterThrowing
package com.aspect;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class AfterThrowingAspect {
@AfterThrowing(throwing = "ex",pointcut = "execution(* com.pojo.*.*(..) )")
public void afterThrowingAspectFunction(Throwable ex){
System.out.println(Here is the AfterThrowing enhancement, which prints exceptions thrown in the target method:+ex); }}Copy the code
@Around
package com.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class AroundAspect {
@Around("execution(* com.pojo.*.*(..) )")
public Object aroundAspectFunction(ProceedingJoinPoint joinPoint) throws java.lang.Throwable {
System.out.println("Here's Around enhancement.");
System.out.println("Around enhancement: Simulation starts transaction before execution of target method...");
Object[] args = joinPoint.getArgs();
if(args ! = null && args.length >1) {
args[0] = "[added prefix]" + args[0];
}
Object rvt = joinPoint.proceed(args);
System.out.println("Around enhancement: Emulation ends transaction after execution of target method...");
if(rvt ! = null && rvt instanceof Integer) rvt = (Integer) rvt * (Integer) rvt;returnrvt; }}Copy the code
3.2.4 Configuration file applicationContext.xml
<? 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <! -- Enable AspectJ support --> < AOP: AspectJ-autoproxy /> <! Scan @component annotations in POJOs for @aspect annotations and other enhanced annotations Such as @before @afterreturning @afterthrowing @around --> <context:component-scan base-package="com.pojo,com.aspect">
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"></context:include-filter>
</context:component-scan>
</beans>
Copy the code
3.2.5 Starting the Test class
package com.test;
import com.pojo.Hello;
import com.pojo.World;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) {
// Load the configuration file applicationContext.xml
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
/ / hello class
Hello hello=(Hello)context.getBean("hello");
hello.foo();
hello.addUser("Xiao Ming"."1000");
try{
hello._functionException(5);
}catch (Exception e){
}
/ / world class
World world=(World) context.getBean("world"); world.bar(); }}Copy the code
3.2.6 Running Results
Here's the Around enhancement: The Around enhancement: The simulation starts the transaction before executing the target method... Before enhancement: the target method to be woven into the enhancement is: foo. Before enhancement: the target method to be woven into the enhancement is: [] Before enhancement: the target object to be woven into the enhancement is: com.pojo.hello @1D2adfbe executes the Hello component's foo() method Around enhancement: After executing the target method, the simulation ends the transaction... AfterReturning: The target method that is woven into the enhancement process is: foo AfterReturning: The parameters of the target method are: [] AfterReturning: The target object woven into the enhancement is com.pojo.hello@1After enhancement: the target method to be woven into the enhancement process is: foo After enhancement: the target method to be woven into the enhancement process is: [] After enhancement: the target object to be woven into the enhancement process is: com.pojo.hello @1D2adfbe here is Around enhancement Around enhancement: Before executing the target method, the simulation starts the transaction... Before enhancement: the target method that is weaved into the enhancement process is: addUser Before enhancement: the parameter of the target method is: [[added prefix] Xiao Ming,1000] Before enhancement: The target object to be woven into enhancement is com.pojo.hello@1D2adfbe execute Hello component addUser addUser: [addUser] AfterReturning: addUser AfterReturning (addUser AfterReturning) : addUser AfterReturning (addUser AfterReturning)1000] AfterReturning: the target object that is woven into enhancement is com.pojo.hello @1D2adfbe where After enhancer: the target method that is weaved into the enhancer is: addUser After enhancer: the target method parameter is: [[added prefix] xiao Ming,1000] After enhancement: The target object to be woven into enhancement is com.pojo.hello@1D2adfbe here is Around enhancement Around enhancement: Before executing the target method, the simulation starts the transaction... Before augment: the target method that is woven into the enhancement process is _functionException. Before augment: The target method takes the following parameters: [5] Before enhancement: The target object to be woven into enhancement is com.pojo.hello@1D2adfbe here is AfterThrowing enhancement processing, to print the exception thrown in the target method: Java. Lang. ArithmeticException: After enhancement: the target method that is woven into the enhancement process is: _functionException After enhancement: The target method takes the following parameters: [5] After enhancement: The target object to be woven into enhancement is com.pojo.hello@1D2adfbe here is Around enhancement Around enhancement: Before executing the target method, the simulation starts the transaction... Before enhancement: the target method that is woven into the enhancement process is: bar Before enhancement: the parameter of the target method is: [] Before enhancement: the target object that is woven into the enhancement process is: com.pojo.world @36902638Execution of the World component's bar() method Around enhancement: After execution of the target method, the simulation ends the transaction... AfterReturning: the target method that is woven into the enhancement process is: bar AfterReturning: The target method parameters are: [] AfterReturning: The target object woven into the enhancement is com.pojo.world @36902638After enhancement: the target method that is woven into the enhancement process is: bar After enhancement: the target method parameters are: [] After enhancement: the target object that is woven into the enhancement process is: com.pojo.world @36902638
Copy the code
Hello.foo (); hello.foo(); Hello. AddUser (” Ming “, “1000”); hello._functionException(5); world.bar(); To save space, just explain hello. AddUser (” Xiao Ming “, “1000”); And hello. _functionException (5); Two are fine, one with two arguments and one with exceptions, hello.foo(); And the world. The bar (); All are the same, as explained in the picture below:
3.3 Spring AOP practice: XML configuration file implementation
3.3.1 Directory Structure
3.3.2 Two POJO classes
package com.pojo;
public class Hello {
public void foo() {
System.out.println("Execute the foo() method of the Hello component");
}
public void addUser(String name, String pass) {
System.out.println(Add a user by executing the Hello component addUser: + name);
}
public void _functionException(int orgin) {
int a = orgin / 0; }}Copy the code
package com.pojo;
public class World {
public void bar() {
System.out.println("Execute the bar() method of the World component"); }}Copy the code
3.3.3 Three Aspect classes
package com.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import java.util.Arrays;
// There are four notifications in this class @before@afterreturning @after@around so it is called FourAdviceTest
public class FourAdviceTest {
public Object aroundFunction(ProceedingJoinPoint joinPoint) throws java.lang.Throwable{
System.out.println(a); System.out.println("Around enhancement: Simulation starts transaction before execution of target method...");
Object[] args = joinPoint.getArgs();
if(args ! = null && args.length >0 && args[0].getClass()==String.class) {
args[0] = "[added prefix]" + args[0];
}
Object rvt = joinPoint.proceed(args);
System.out.println("Around enhancement: Emulation ends transaction after execution of target method...");
if(rvt ! = null && rvt instanceof Integer) rvt = (Integer) rvt * (Integer) rvt;return rvt;
}
public void beforeFunction(JoinPoint joinPoint){
System.out.println("Fouradvicetest-before Enhancement: Simulating execution permission checking");
System.out.println("Four Advicetest-before enhancement: The target method woven into the enhancement process is:"+joinPoint.getSignature().getName());
System.out.println("Four Advicetest-before enhancement: The argument to the target method is:+ Arrays.toString(joinPoint.getArgs()));
System.out.println("Four Advicetest-before enhancement: The target object woven into the enhancement process is:"+joinPoint.getTarget());
}
public void afterReturningFunction(JoinPoint joinPoint, Object rvt){
System.out.println("AfterReturning Enhancement: Get the return value of the target method:"+rvt);
System.out.println("AfterReturning Enhancement: Simulated logging capabilities...");
System.out.println("AfterReturning enhancement: The target method of being woven into enhancement is:"+joinPoint.getSignature().getName());
System.out.println("AfterReturning enhancement: The parameters of the target method are:"+ Arrays.toString(joinPoint.getArgs()));
System.out.println("AfterReturning enhancement: The target object woven into enhancement is:"+joinPoint.getTarget());
}
public void afterFunction(JoinPoint joinPoint){
System.out.println("After enhancement: Release resources After simulation method ends...");
System.out.println("After enhancement: The target method woven into the enhancement process is:"+joinPoint.getSignature().getName());
System.out.println("After enhancement: The target method parameter is:"+ Arrays.toString(joinPoint.getArgs()));
System.out.println("After enhancement: The target object woven into the enhancement process is:"+joinPoint.getTarget()); }}Copy the code
package com.aspect;
public class RepairAspect {
public void doRecoveryActions(Throwable ex){
System.out.println("Print exception:"+ex); }}Copy the code
package com.aspect;
// There is a notification @before in this class called SecondAdviceTest because it is the second @before
public class SecondAdviceTest {
public void authority(String aa){
System.out.println("Secondadvicetest-before Enhancement: Simulated Execution check"+"The parameters of the target method are:"+aa); }}Copy the code
3.3.4 Spring configuration file appliationContext.xml
<? 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<aop:config>
<aop:pointcut id="myPointcut" expression="execution(* com.pojo.*.*(..) )"></aop:pointcut>
<aop:aspect id="fourAdviceAspect" ref="fourAdviceBean" order="2">
<aop:after pointcut="execution(* com.pojo.*.*(..) )" method="afterFunction"></aop:after>
<aop:before pointcut="execution(* com.pojo.*.*(..) )" method="beforeFunction"></aop:before>
<aop:after-returning pointcut="execution(* com.pojo.*.*(..) )" method="afterReturningFunction"
returning="rvt"></aop:after-returning>
<aop:around pointcut="execution(* com.pojo.*.*(..) )" method="aroundFunction"></aop:around>
</aop:aspect>
<aop:aspect id="secondAdviceAspect" ref="secondAdviceBean" order="1">
<aop:before pointcut="execution(* com.pojo.*.*(..) ) and args(aa)" method="authority"></aop:before>
</aop:aspect>
<aop:aspect id="afterThrowingAdviceAspect" ref="afterThrowingAdviceBean">
<aop:after-throwing pointcut-ref="myPointcut" method="doRecoveryActions" throwing="ex"></aop:after-throwing>
</aop:aspect>
</aop:config>
<bean id="fourAdviceBean" class="com.aspect.FourAdviceTest"></bean>
<bean id="secondAdviceBean" class="com.aspect.SecondAdviceTest"></bean>
<bean id="afterThrowingAdviceBean" class="com.aspect.RepairAspect"></bean>
<bean id="hello" class="com.pojo.Hello"></bean>
<bean id="world" class="com.pojo.World"></bean>
</beans>
Copy the code
3.3.5 Test Start the class
package com.test;
import com.pojo.Hello;
import com.pojo.World;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) {
// Load the configuration file applicationContext.xml
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
/ / hello class
Hello hello = (Hello) context.getBean("hello");
hello.foo();
hello.addUser("Xiao Ming"."1000");
try {
hello._functionException(5);
} catch (Exception e) {
}
/ / world class
World world = (World) context.getBean("world"); world.bar(); }}Copy the code
3.3.6 Running Results
Basically the same as using annotations (that is, printing statements are a little different), which is skipped here.
Four, summary
This paper is divided into three parts, respectively introduced the basic knowledge of AOP, with AspectJ AOP as an example to introduce static AOP, with Spring AOP as an example to introduce dynamic AOP, which focuses on Spring AOP, the full text from AOP to AspectJ AOP, and then to Spring AOP, Hopefully useful for Java learners. Play code every day, progress every day