What is AOP?

Speaking of AOP, what exactly is AOP? AOP or aspect oriented programming, compared with OOP, object-oriented programming, because is the most basic unit in object-oriented classes, instances, naturally we will think of AOP is probably the most basic units in the so-called section, you may ask, what is the cross section and stuff, I want to say, don’t understand it doesn’t matter, now I will talk about below. Let’s take a look at Spring’s definition of AOP:

Aspect oriented — Spring provides rich support for aspect oriented programming to allow cohesive development by separating the business logic of the application from system-level services such as auditing and Transaction management. Application objects do what they are supposed to do — complete the business logic — and no more. They are not responsible for (or even aware of) other system-level concerns, such as logging or transaction support.

As mentioned above, AOP can separate the business logic of the system from the system services (logging, security, etc.), which I think is not difficult to understand (using the proxy pattern), but the point is why separate the two? Or what good would it do?

In daily software development, take the log as an example, the development of a system software must be logged, otherwise in case of any bugs in the system, you do not know where the problem is. For a small chestnut, landing when you develop a function, you may need to be performed before and after the user login permissions validation and will check the information (user name, password, request landing time, IP address, etc.) are recorded in the log file, when the user logged in, when he visited some other functions, also need to check the validity. Think about it, when the system is very huge, specially in the system authentication code is very much, and very scattered, and we want to these permissions can be check, logging and other non-business logic function of independent split apart, and where it is needed when the system is running (points) for dynamic insert operation, don’t need to ignore it, So AOP is an idea that can solve this situation!

Here is a good illustration of the process:

Basic concepts in AOP

I have to say that AOP concepts are really numerous and hard to understand, but don’t worry, you’re smart enough to beat them.

  • Notice (Adivce)

There are five types of notifications:

  • Before is called Before the method is called

  • After calls the notification After the method completes, whether or not the method executed successfully

  • After-returning calls notification After successful execution of a method

  • After-throwing calls notification After a method throws an exception

  • Around notifies well, contains the notifying method, and performs custom behavior before and after the notifying method call

    We might ask, is the notification code in the corresponding system a method, object, class, interface or something? I want to say, in fact is not, you can understand the notice is correspond to what we use in our everyday life, such as “so-and-so, you come to school on September 1, 2019 to ‘, notice more embodies a kind of tells us when (what) system, a stipulated time, at some point in time in operation of the system (such as thrown exception! Method execution before! Is not a method in the corresponding code! Not a method in the corresponding code! Not a method in the corresponding code!

  • Pointcut

    Ha ha, this may be easier for you to understand, but the pointcuts in Spring AOP are indeed methods in the corresponding system. But this method is defined in the section, and is usually used together with the advice that makes up the section.

  • Join point

    For example: method invocation, method execution, field setting/fetching, exception handling execution, class initialization, and even a point in a for loop

    In theory, any point in the execution of a program can be used as a weaving point, and all of these execution points are Joint points

    But Spring AOP currently only supports method execution. Join points are where you are going to execute the pointcut and cut advice in the system (typically a method, a field).

  • Aspect

    An aspect is a collection of pointcuts and advice, typically as a separate class. Together, notifications and pointcuts define everything about the aspect, when, when, and where it completes.

  • Introduction

    References allow us to add new methods or properties to existing classes

  • Weaving

    Assemble the aspect to create a notified object. This can be done at compile time (using the AspectJ compiler, for example) or at run time. Spring, like other pure Java AOP frameworks, is woven at run time.

AOP support in Spring

First of all, the implementation of AOP ideas is generally based on the proxy pattern. In JAVA, the JDK dynamic proxy pattern is generally adopted. But as we all know, the JDK dynamic proxy pattern can only proxy interfaces. Therefore, Spring AOP will switch this way, because Spring AOP supports both CGLIB, ASPECTJ, and JDK dynamic proxies. By default, Spring AOP uses JDK dynamic proxies when your real object has an implementation interface, and CGLIB proxies otherwise.

  • Spring AOP will use JDK dynamic proxies to generate AOP proxy classes if the target object’s implementation class implements the interface.
  • If the target object’s implementation class does not implement the interface, Spring AOP will use CGLIB to generate the AOP proxy class — but the selection process is completely transparent and unconcerned to the developer.

Four, said so much, to some biscuits to quench thirst! Directly on the code!

So do cookies quench your thirst?

  • Define topic interfaces whose methods can be ourThe join
package wokao666.club.aop.spring01; Public void login(); public void login(); Public void download(); }Copy the code
  • Define the implementation class, which is the real agent in the proxy pattern (if you are involved in the daigou, this is like your role in the daigou).
package wokao666.club.aop.spring02;

import wokao666.club.aop.spring01.Subject;

public class SubjectImpl implements Subject {

	public void login() {
		
		System.err.println("Borrow a book from...");
		
	}

	public void download() {
		
		System.err.println("Downloading..."); }}Copy the code
  • Define sections (sections with pointcuts and advice)
package wokao666.club.aop.spring01; import org.aspectj.lang.JoinPoint; Public class PermissionVerification {/** * PermissionVerification * @param args login parameter */ public voidcanLogin() {// do some login verification system.err. Println () {"I'm checking it out !!!!"); } /** * Do some processing after the validation (whether it is successful or not) * @param args permission validation parameter */ public voidsaveMessage() {// do some post-processing system.err. Println () {"I'm working on it !!!!"); }}Copy the code
  • Let’s take a look at oursSpringAOP.xmlfile
<? 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"
    xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
        
        <bean id="SubjectImpl1" class="wokao666.club.aop.spring02.SubjectImpl" />
        <bean id="SubjectImpl2" class="wokao666.club.aop.spring02.SubjectImpl" />
        <bean id="PermissionVerification" class="wokao666.club.aop.spring01.PermissionVerification"/> <aop:config> <! > <aop:aspect id="do" ref="PermissionVerification"> <! -- define the pointcut, followed by the expression language, which means that all methods defined in the interface will be executed --> < AOP :pointcut id="point" expression="execution(* wokao666.club.aop.spring01.Subject.*(..) )"/ > <! -- define advice --> <aop:before method="canLogin" pointcut-ref="point" />
                <aop:after method="saveMessage" pointcut-ref="point" />
            </aop:aspect>
        </aop:config>
</beans>
Copy the code
  • Since I build on MAVEN, let’s take a look at ourspom.xmlfile
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> < modelVersion > 4.0.0 < / modelVersion > < groupId > wokao666. The club < / groupId > < artifactId > aop < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < packaging > jar < / packaging > < name > aop < / name > < url > http://maven.apache.org < / url > <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <dependencies> <groupId> </groupId> </groupId> <artifactId>junit</artifactId> <scope>test</groupId> </groupId> </groupId> </groupId> </groupId> </groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </version> </version> </dependency> <groupId>cglib</ artifactId> </artifactId> < version > 3.2.4 < / version > < / dependency > < / dependencies > < project >Copy the code
  • Finally, take a look at our test class and the results
package wokao666.club.aop.spring01;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	
	public static void main(String[] args) {
		ApplicationContext ctx = 
	      new ClassPathXmlApplicationContext("SpringAOP.xml");
	  
				Subject subject1 = (Subject)ctx.getBean("SubjectImpl1");
				Subject subject2 = (Subject)ctx.getBean("SubjectImpl2");
				
				subject1.login();
				subject1.download();
				
				
				System.err.println("= = = = = = = = = = = = = = = = = ="); subject1.login(); subject1.download(); }}Copy the code
On March 13, 2018 afternoon 4:59:44 org. Springframework. Context. Support. The ClassPathXmlApplicationContext prepareRefresh information: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@31cefde0: startup date [Tue Mar 13 16:59:44 CST 2018]; Root of context hierarchy 2018 4:59:45 afternoon org. Springframework. Beans. Factory. XML. XmlBeanDefinitionReader loadBeanDefinitions information: Loading XML bean Definitions from class path resource [springAop.xml Borrow books in the... I'm working on it !!!! I'm checking it !!!! Download... I'm working on it !!!! ================== I'm checking !!!! Borrow books in the... I'm working on it !!!! I'm checking it !!!! Download... I'm working on it !!!!Copy the code

I think that’s just scratching the surface. If you want to learn more, you can take a look at the source analysis of the JDK dynamic proxy (which is very clever, and uses second-level caching, I was going to write, but I will leave it to the next article!). Spring AOP source analysis, and so on. Of course, the above implementation is based on old-fashioned XML files and is not recommended. Why? I think when you get a big system, there will bea lot of beans and XML files in the system, which will not be easy to maintain and manage, I suggest using annotation-based AOP programming is better!

Okay, I wanted to finish, but before I could close Eclipse, I found a small problem. Since pointcuts are the methods that need to be executed, how do we get the data (or the validation parameters) for the join points? “, here recommended a blog post, I will not write! Friends, come on together!

Spring AOP advises the passing of parameters