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

How to use AspectJ in SpringAOP

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

Share

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

This article is about how to use AspectJ in SpringAOP. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

AspectJ is an AOP framework based on Java language. Spring2.0 has added support for AspectJ pointcut expressions since then. Because Aspectj didn't appear at the time of Spring1.0.

New support for annotations has been added in AspectJ1.5, allowing you to define aspects directly in the Bean class. The new version of the Spring framework suggests that we all use AspectJ to develop AOP, and provides very flexible and powerful pointcut expressions

Of course, the concepts related to Spring's own AOP or AspectJ are the same.

Annotation configuration

Dependency Import:

Org.springframework spring-aspects 5.2.2.RELEASE

Notification Typ

The type of notification provided by @ AspectJ: @ Before pre-notification executes @ AfterReturning post notification before the original method executes, performs @ Around surround notification before the original method executes, and completely intercepts the execution of the original method. Logic can be added before and after execution, or the original method @ AfterThrowing throws the notification, and the @ After final final notification is executed when the original method is abnormal. Regardless of whether it is abnormal or not, @ DeclareParents introduction notification is executed after the original method call, which is equivalent to IntroductionInterceptor (just know it)

Define tangent point

Define tangent points through the execution function

Syntax: execution (access modifier returns type method name argument exception)

Example of an expression:

Match all class public methods: execution (public * * (..)) The first * indicates the return value.. Indicates that any parameter of any type matches all methods under the specified package: execution (* cn.xxx.dao.* (..)) The first one wants to * indicate that the ignore permission and the return value type match all methods under the specified package: execution (* cn.xxx.dao..* (..)) Contains subpackages to match all methods of the specified class: execution (* cn.xxx.service.UserService.* (..)) Match all class methods that implement a specific interface: execution (* cn.xxx.dao.GenericDAO+.* (..)) Match all methods at the beginning of save: execution (* save* (..))

Advance notice

Pom dependencies:

Org.springframework spring-context 5.2.2.RELEASE org.springframework spring-aspects 5.2.2.RELEASE org.springframework spring-test 5.2.2.RELEASE test org.springframework spring-test 5.2.2.RELEASE test junit junit 4.13 test

Xml needs to add aop namespace and xsd:

Test:

RunWith (SpringJUnit4ClassRunner.class) @ ContextConfiguration ("classpath:applicationContext.xml") public class Test1 {@ Autowired PersonDao personDao; @ Test public void test () {personDao.delete (); personDao.update ();}}

Facet class:

Import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;@Aspectpublic class MyAspect {/ / means that all methods under PersonDao are used as pointcuts @ Before (value = "execution (* com.yh.demo1.PersonDao.* (..)")) Public void beforeAdvice () {System.out.println ("before code run.");}}

When we need to get pointcut information (enhanced code), we can add parameters to the notification, like this

@ Aspectpublic class MyAspect {@ Before (value = "execution (* com.yh.demo1.PersonDao.* (..)") Public void beforeAdvice2 (JoinPoint point) {System.out.println ("before code run2." + point);}}

Post Notification:

/ when you need to get the return value of the original method, you can add the returning parameter to the annotation to specify the parameter name Aspectj will automatically put the return value in the parameter @ AfterReturning (value = "execution (* com.yh.demo1.PersonDao.delete (..)", returning = "result") public void afterAdvice (Object result) {System.out.println ("after the deletion method executes. The return value is:" + result);}

Post notification can get the return value of the target method

Surround notification:

@ Around (value = "execution (* com.yh.demo1.PersonDao.insert (..)") public void aroundAdvice (ProceedingJoinPoint point) throws Throwable {/ / code. System.out.println ("surround the front..."); / / execute the original method _ _ when you need to get the return value, you can declare that the variable receives Object result = point.proceed (); System.out.println ("original method return value:" + result); / / code. System.out.println ("surround the rear.");}

The biggest difference between a surround notification and other notifications is that a surround notification can control whether the original method is called.

Note: the parameter type must be ProceedingJoinPoint, otherwise the original method cannot be executed

Exception notification

@ AfterThrowing (value = "execution (* com.yh.demo1.PersonDao.save (..)", throwing = "e") public void exceptionHandler (JoinPoint point,Exception e) {System.out.println (point + "method occurrence" + e.getMessage () + "exception");}

The notification is executed only when it appears in the method. If you need to obtain exception information, add throwing to the annotation to specify the parameter name.

We can use surround + exception notification to handle database transactions, open and commit the transaction in the surround, and roll back the transaction in the exception notification. Of course, Spring has encapsulated the transaction and does not need to write its own

Final notice

@ After (value = "execution (* * delete (..)") public void afterRun () {System.out.println ("final");}

The final notification is called after, which is executed after the original method is called, regardless of whether there is an exception in the original method or not

The subsequent setting is called afterReturning, which means that the execution will not be executed until it is returned successfully.

Expression with logic: allows the user to logically manipulate the operator in the expression, and & & or | | No!

Example:

/ * execution (* cn.xxx.service.UserDao.insert (..) | | execution (* cn.xxx.service.UserDao.delete (..) execution (* cn.xxx.service.UserDao.*nsert (..)) & & execution (* cn.xxx.service.UserDao.inser* (..)! execution (* cn.xxx.service.UserDao.insert (..)) * / 2 | 4 pointcut names

Tangent point naming

Suppose that when multiple notifications are applied to the same pointcut, we need to write execution expressions repeatedly, and when we want to modify the pointcut later, multiple notifications need to be modified, which is very troublesome to maintain. We can complete the reuse and unified operation of the pointcut by specifying the name of the pointcut, so as to improve the efficiency of development and maintenance.

/ / define the name of the pointcut method @ Pointcut (value = "execution (* com.yh.demo1.PersonDao.save (..)") private void savePointcut () {} @ Pointcut (value = "execution (* pointcut (..)") private void deletePointcut () {}

Multiple notifications are applied to the same pointcut:

/ / use named pointcut @ Before (value = "savePointcut ()") public void beforeAdvice () {System.out.println ("before code run.");} / / use named pointcut @ Around (value = "savePointcut ()") public void beforeAdvice2 (ProceedingJoinPoint point) throws Throwable {System.out.println ("before"); point.proceed (); System.out.println ("wrap after")

One notification is applied to multiple pointcuts

/ / multiple pointcuts @ After corresponding to the same notification (value = "savePointcut () | | deletePointcut ()") public void afterAdvice () {System.out.println ("after code run.");}

XML configuration

The jar required for XML configuration, the dependencies between objects and the expression are all written in the same way, just in a different way

Xml:

Notification class:

Import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.JoinPoint;public class XMLAdvice {public void before (JoinPoint pointcut) {System.out.println ("pre-notification tangent:" + pointcut);} public void afterReturning (JoinPoint point,Object result) {System.out.println ("post notification tangent:" + point);} public void after (JoinPoint point) {System.out.println ("final notification tangent:" + point) } public void exception (JoinPoint point,Throwable e) {System.out.println ("exception Notification: + e +" tangent: "+ point);} public void around (ProceedingJoinPoint point) throws Throwable {System.out.println (" before "orbit"); point.proceed (); System.out.println ("after orbit");}}

You will find that neither XML nor annotations need to specify the proxy and the target object manually. Aspectj will obtain the target object information from the pointcut and automatically create the proxy.

AspectJ is the more popular way at present, whether to use XML or annotation needs to be based on the specific circumstances of the project. Team collaborative development recommends xml.

Thank you for reading! This is the end of the article on "how to use AspectJ in SpringAOP". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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