Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Spring AOP?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what is Spring AOP". In daily operation, I believe many people have doubts about what is Spring AOP. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what is Spring AOP?" Next, please follow the editor to study!

Overview

AOP is an acronym for aspect-oriented programming, translated as aspect-oriented programming. Each part of the business logic can be isolated by using AOP, which reduces the coupling between the various parts of the business logic, improves the reusability of the program, and improves the efficiency of development at the same time. To put it simply, AOP means adding new functions to the backbone without modifying the source code.

Underlying principle ‍‍

The underlying AOP uses dynamic proxies: JDK dynamic proxies when there are interfaces, and CGLIB bytecode dynamic proxies when there is no interface.

JDK dynamic agent

Brief introduction

To use the JDK dynamic proxy, you need to create a proxy object using the newProxyInstance method in the Proxy class in JDK. The methods are as follows:

Static Object newProxyInstance (ClassLoader loader, Class [] interfaces, InvocationHandler h)

The three parameters of the newProxyInstance method indicate:

Loader defines a class loader for a proxy class

List of interfaces to be implemented by the interfaces proxy class (can have more than one)

H assigns the handler for method calls (the functionality to be enhanced is implemented here)

The newProxyInstance method returns an instance of the proxy class for the specified interface.

There is an invoke method in the InvocationHandler interface to implement the enhanced functionality:

Public Object invoke (Object proxy, Method method, Object [] args)

Throws Throwable

The three parameters of the invoke method indicate:

Proxy represents a proxy object

Method represents the enhanced method

Args is the parameter of the method. If not, null.

Sample code

The code structure is as follows:

└─ src

└─ com

└─ spring5

JDKProxy.java

UserDao.java

UserDaoImpl.java

UserDao interface:

Public interface UserDao {

Int add (int a pencil int b)

String update (String id)

}

UserDaoImpl class:

JDKProxy class:

Running result:

Method is executed before the. Add: parameters passed... [1, 2]

I am add...

Method is executed after the. Com.spring5.UserDaoImpl@355da254

Result:3

CGLIB bytecode dynamic proxy

Brief introduction

The use of CGLIB bytecode dynamic proxy is not limited by the interface that the proxy class must implement, and its underlying layer uses the ASM bytecode generation framework. Advantages and disadvantages of CGLIB dynamic agent:

Using bytecode technology to produce agents has higher reflection efficiency than JAVA.

Methods declared as final cannot be proxied because the principle is to dynamically generate subclasses of the proxied class

You need to implement the interface MethodInterceptor, and then override the intercept method:

Object intercept (Object proxy, Method method, Object [] args, MethodProxy arg3) throws Throwable

The parameter description of the intercept method:

The proxy class instance generated by proxy CGLIB, which is also a subclass of the target object, is equivalent to overriding the parent class method

Method proxied method

Args method parameters

A proxy reference to a method for the generated proxy class

The intercept method returns

In addition, the Enhancer class is used, which is a bytecode enhancer in Cglib. First, adjust its setSuperclass () to set the surrogate class as the parent class, then adjust the setCallback function to execute the intercept method, and finally call create () to generate the proxy class.

Sample code

The code structure is as follows:

└─ src

└─ com

└─ spring5

CglibProxy.java

User.java

User class:

Public class User {

Public void sleep () {

System.out.println ("I want to sleep...")

}

}

CglibProxy class:

Running result:

Undress before going to bed

I want to sleep...

Get up and get dressed.

AOP operation

Overview

Several terms related to AOP:

Connection point

Which methods in the class can be enhanced? these methods are called join points

Entry point

The method that is actually enhanced is called the pointcut.

Notice

The logical part of the actual enhancement is called notification, which can be divided into five types: pre-notification, post-notification, surround notification, exception notification and final notification, in which the final notification is equivalent to the finally of JAVA.

Cut plane

Apply notifications to the pointcut process

AspectJ

AspectJ is not a part of Spring, but an independent AOP framework. Generally, AspectJ and Spirng framework are used together for AOP operation. Enhancement means acting as an agent.

Preparatory work

The following four Jar packages need to be introduced when performing AOP operations

Com.springsource.net.sf.cglib-2.2.0.jar

Com.springsource.org.aopalliance-1.0.0.jar

Com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

Spring-aspects-5.2.6.RELEASE.jar

All packages after introduction are as follows:

Com.springsource.net.sf.cglib-2.2.0.jar

Com.springsource.org.aopalliance-1.0.0.jar

Com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

Spring-aspects-5.2.6.RELEASE.jar

Commons-logging-1.1.1.jar

Spring-aop-5.2.6.RELEASE.jar

Spring-beans-5.2.6.RELEASE.jar

Spring-context-5.2.6.RELEASE.jar

Spring-core-5.2.6.RELEASE.jar

Spring-expression-5.2.6.RELEASE.jar

The pointcut expression of AspectJ is described as follows:

Action

Know which method in which class to enhance

Grammar

Execution ([permission modifier] [return type] [class full path] [method name] ([parameter list]))

Example

Annotation-based implementation

Main steps

The main steps are as follows:

In the spring configuration file, turn on annotation scanning

The context space for context and aop needs to be introduced in XML.

Create User and UserProxy objects using annotations

Add an annotation @ Aspect to the enhanced class

Open the build proxy object in the spring configuration file

When the Aspectj generation object is enabled, the @ aspect annotation is scanned in the code.

Configure different types of notifications

Use @ Before, @ AfterReturning, @ Around, @ AfterThrowing, and @ After annotations on the notification method, combined with pointcut expression configuration.

@ after is executed after the method is executed (even if there are exceptions), and @ afterReturning is executed after the return value (if any exceptions are not executed).

Sample code

Code structure:

User class:

UserProxy class:

Test class:

No exception returns the result:

Before the Around surround

Pre-notification before

I am add

After Around surround

Final notification to after

Post notification (return notification) afterReturning

The result is returned if there is an exception:

Before the Around surround

Pre-notification before

Final notification to after

Exception notification afterThrowing

Java.lang.ArithmeticException: / by zero

Same pointcut extraction

Use the @ Pointcut tag

Multiple enhancement classes enhance the same method

Use the @ Order annotation to set the enhancement class priority. The smaller the numeric type value, the higher the priority.

@ Component

@ Aspect

@ Order (1)

Public class PersonProxy {}

Fully annotated development

Add the @ EnableAspectJAutoProxy annotation to the startup configuration class:

@ Configuration

@ ComponentScan (basePackages = {"com.spring5"})

@ EnableAspectJAutoProxy (proxyTargetClass = true)

Public class ConfigAop {

}

Implementation based on configuration file

Concrete steps

Create enhanced classes and enhanced classes, and create related methods

Configure two class objects in the spring configuration file

Configure AOP in the spring configuration file

Sample code

The code structure is as follows:

Student class:

StudentProxy class:

Test class:

Bean.xml:

Running result:

I am before...

I want to buy a book...

I am afterReturn...

At this point, the study of "what is Spring AOP" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report