SpringAOP

Why should we use AOP (aspect oriented programming)? When we complete the actual project in reality, we always need to be done in an “action”, before, after or do something, such as when we are running the program, we want to log, or output after every method call in a word, this means that each time we carry out a “action” need to do the same thing, This leads to a lot of useless, repetitive actions by programmers, and AOP came into being in this situation.

AOP overview

AOP, which is the abbreviation of Aspect Oriented Rrogramming, means: section-oriented programming, through pre-compilation and runtime dynamic proxy implementation program function unified maintenance of a technology. AOP can isolate the various parts of the business drain, thus reducing the coupling between business logic, improving the reuse of programs, and improving the efficiency of development.

AOP and OOP are two different design ideas. OOP (object oriented programming) abstracts and encapsulates entities and their attributes and behaviors in business processing process to obtain clear and efficient logical unit division. AOP is for the business process in the section of the extraction, is facing a certain step or stage in the business process, to obtain the isolation effect of low coupling between the various parts of the logical process.

The benefit of faceted programming is to reduce duplication and focus on the business. It is a complement to object-oriented programming. I sorted out some information, and friends in need can click to get it directly.

Java Basics

22 Java Architect Core books

Learning routes and materials from 0 to 1Java

1000+ questions from 2021

Core principles and use cases

Principle: Dynamic proxies are used to add logic before and after method execution or when exceptions occur.

Use:

Transaction processing: start the transaction, close the transaction, and roll back the transaction if an exception occurs..... Permission judgment: Before executing the method, determine whether the user has the permission. Log processing; . Transaction processing: start the transaction, close the transaction, and roll back the transaction if an exception occurs..... Permission judgment: Before executing the method, determine whether the user has the permission. Log processing; .Copy the code

Basic concepts of AOP (The term for Spring)

0. Enhancement: Inject some logic code into each program to enhance the function of the original program.

1. JoinPoint (JoinPoint) : A method in a class that can be enhanced. This method is called a JoinPoint.

2. Pointcuts: the methods in a class that are actually enhanced.

3. Advice: What a facet does at a particular join point, simply “enhance.” It can be divided into pre-method notification, post-method notification, surround notification and so on.

Aspect: The process of adding advice to a pointcut is called Aspect.

5. Target: The Target object of the agent, that is, the class of the method to be enhanced.

6. Proxy: A Proxy object created after notification is applied to the target object.

SpringAOP implementation

Many frameworks implement AOP programming ideas. Spring is just one of those that can do faceted programming. AspectJ is also a section-oriented framework that is simpler, more convenient, and supports annotated development. So Spring has brought AspectJ’s implementation of AOP back into its framework.

When developing with AOP in Spring, AspectJ’s implementation is typically used. There are five common types of notifications:

  • Pre-notification: execute before method execution;
  • Post notification: execute after method execution;
  • Circular notification: both before and after execution;
  • Abnormal notice: abnormal notice;
  • Final notification: for example, after return.

The use of SpringAOP

Import the JAR for AspectJ that implements AOP

<! Spring implements AOP based on the Aspects framework. <dependency> <groupId>org.spring Framework </groupId> <artifactId> Spring Aspects </artifactId> < version > 5.2.2. RELEASE < / version > < / dependency >Copy the code

XML configuration implementation based on AspectJ

All configuration is done in the spring.xml file.

1. Create an enhanced class.

import org.aspectj.lang.ProceedingJoinPoint; Public class Aop {public void doLog() {system.out.println ("===== save log ====="); {} public void the commit () System. The out. Println (" = = = = = to commit the transaction = = = = = "); } public void around(ProceedingJoinPoint ProceedingJoinPoint) {system.out.println ("====== before ======"); try { proceedingJoinPoint.proceed(); / / call} catch my way (Throwable Throwable) {Throwable. PrintStackTrace (); } system.out. println("====== method after notification ======"); } public void throwable(throwable throwable) {system.out.println ("====== error ======"); System.out.println(throwable.getMessage()); }}Copy the code

2. Hand over classes with enhancements to Spring for management

<? The 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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <! - give Spring classes with notice (Advice) management - > < bean id = "aop" class = "com. CWD. Spring4pro. Not. Aop. Aop" > < / bean > <! -- Weave in here, i.e. Aspect: Add the advice to the pointcut --> </beans>Copy the code

3. Configure aspects

Start with an enhanced class, the Target

import org.springframework.stereotype.Component; // Target: the Target object of the proxy, @Component(value = "target") public class target {/* Joinpoint (Joinpoint) Public void pointCut() {system.out.println (" This is a save operation!! ); return; }}Copy the code

Add advice to the pointcut.

<! --> <aop:config> <! The return value saveUser(..) is set before the pointcut execution expression. Indicates the method to enhance.. Said parameters - > < aop: pointcut id = "pointcut expression =" execution "(. * com. CWD spring4pro. Demo. Target. The pointcut (..) ) "/ > <! <aop:aspect ref="aop"> <! <aop:before method=" pointcut "/> </aop:aspect> </aop:config>Copy the code

Five notification types are configured

1. Pre-notification

<! - weave - > < aop: config > < aop: pointcut id = "pointcut expression =" execution "(. * com. CWD spring4pro. Demo. Target. The pointcut (..) )"/> <aop:aspect ref="aop"> <! <aop:before method=" pointcut "/> </aop:aspect> </aop:config>Copy the code

2. Post notification

<! - weave - > < aop: config > < aop: pointcut id = "pointcut expression =" execution "(. * com. CWD spring4pro. Demo. Target. The pointcut (..) )"/> <aop:aspect ref="aop"> <! <aop:after method="commit" pointcut-ref=" pointcut "/> </aop:aspect> </aop:config>Copy the code

3. Surround notifications

<! - weave - > < aop: config > < aop: pointcut id = "pointcut expression =" execution "(. * com. CWD spring4pro. Demo. Target. The pointcut (..) )"/> <aop:aspect ref="aop"> <! --> <aop:around method="around" pointcut-ref=" pointcut "/> </aop:aspect> </aop:config>Copy the code

4. Exception notification

Public void pointCut() {system.out.println (" This is a save operation!! ); int a = 10 / 0; return; }Copy the code
<! - weave - > < aop: config > < aop: pointcut id = "pointcut expression =" execution "(. * com. CWD spring4pro. Demo. Target. The pointcut (..) )"/> <aop:aspect ref="aop"> <! /> </aop:aspect> </aop:aspect> </aop:config>Copy the code

5. Final notice

<! - weave - > < aop: config > < aop: pointcut id = "pointcut expression =" execution "(. * com. CWD spring4pro. Demo. Target. The pointcut (..) )"/> <aop:aspect ref="aop"> <! < AOP: returning method=" return "pointcut-ref=" pointcut "/> </ AOP :aspect> </ AOP :config>Copy the code

The final notification is usually executed after return.

Annotations to realize

Enable AOP annotation scanning

<! < AOP: Aspectj-autoproxy />Copy the code

Configure in the notification class as follows:

import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; @component // Gives this class to Spring to manage @aspect // marks this class as the notification class public class Aop {@before ("execution(*) com.cwd.spring4pro.demo.Target.pointCut(..) ) "public void doLog () {System. Out. Println (" = = = = = save log = = = = ="); } @After("execution(* com.cwd.spring4pro.demo.Target.pointCut(..) ) "public void the commit () {System. Out. Println (" = = = = = to commit the transaction = = = = ="); } public void around(ProceedingJoinPoint ProceedingJoinPoint) {system.out.println ("====== before ======"); try { proceedingJoinPoint.proceed(); / / call} catch my way (Throwable Throwable) {Throwable. PrintStackTrace (); } system.out. println("====== method after notification ======"); } @AfterThrowing(value = "execution(* com.cwd.spring4pro.demo.Target.pointCut(..) )",throwing =" throwing ") public void throwable(throwable) {system.out.println ("====== "====== "); System.out.println(throwable.getMessage()); } @AfterReturning("execution(* com.cwd.spring4pro.demo.Target.pointCut(..) ) "public void returnAfter () {System. Out. Println (" = = = = = = = = = = =" after the return); }}Copy the code

The last

All read here, feel the article is helpful to you remember to click a like, thank you for your support!