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 Spring to open the location where annotations AOP supports placement

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

Share

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

This article will explain in detail how to use Spring to open the location of AOP support for annotations. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Spring enables the location of the support for annotations AOP

If you put the aop in springmvc, you need to write in the configuration file of springmvc to enable aop instead of the configuration file of spring

Recently use aop to log controller.

But it didn't work.

It turned out that it was because my aop was written in the controller layer (in the springmvc container-web)

The configuration of enabling aop is written in spring (applicationContext.xml).

So it doesn't work. It needs to be enabled in the configuration file of springmvc.xml.

Spring AOP Annotation configuration starts AOP configuration

To use AspectJ annotations in Spring applications, the following support is required:

1. Include AspectJ class libraries under classpath: aopalliance.jar, aspectj.weaver.jar and spring-aspects.jar

two。 Add aop Schema to the root element of the Bean profile.

3. Define an empty XML element in the Bean configuration file

Note: when the Spring IOC container detects an element in the Bean configuration file, it automatically creates a proxy for the Bean that matches the AspectJ section.

Declare the section with AspectJ annotations

To declare AspectJ aspects in Spring, simply declare them as Bean instances in the IOC container. When the AspectJ aspects are initialized in the Spring IOC container, the Spring IOC container creates proxies for those Bean that match the AspectJ aspects.

In the AspectJ annotation, the aspect is just a Java class with the @ Aspect annotation. Notification is a simple Java method that is annotated with some kind of annotation.

AspectJ supports five types of notification comments:

@ Before: pre-notification, executed before the method is executed

@ After: post notification, executed after the method is executed

@ AfterRunning: returns the notification, which is executed after the method returns the result

@ AfterThrowing: exception notification, after the method throws an exception

@ Around: surround the notification and execute around the method

Advance notice

Advance notification: a notification that is executed before the execution of a method.

The preceding notification uses the @ Before annotation and takes the value of the pointcut expression as the annotation value.

/ * declare this class as an aspect: * 1. Use the annotation "@ Repository" to put the class into the IOC container * 2. Use the annotation @ Aspect to declare the class as a section * * to set the priority of the section: * 3. Use the annotation "@ Order (number)" to specify the preceding priority. The lower the value, the higher the priority * / @ Order (1) @ Aspect@Repositorypublic class DaoLogAspect {/ * declares that the method is a pre-notification: executing the *'@ Before' identification method before the start of the target method is a pre-notification, and the pointcut expression indicates the execution of the insert (User user) method of the UserDao class. * / @ Before ("execution (public xyz.huning.spring4.aop.dao.User xyz.huning.spring4.aop.dao.impl.UserDao.insert (xyz.huning.spring4.aop.dao.User))") public void beforeInsert () {System.out.println ("--beforeInsert-");}} write AspectJ pointcut expressions with method signatures

The most typical pointcut expression is to match various methods based on the signature of the method:

Execution * xyz.huning.spring4.aop.dao.impl.UserDao.* (..): matches all the methods declared in UserDao, with the first * representing any modifier and any return value. The second * represents any method. .. Match any number of parameters. If the target class and interface are in the same package as the aspect, the package name can be omitted.

Execution public * UserDao.* (..): matches all public methods of the UserDao class.

Execution public double UserDao.* (..): matches the method in UserDao that returns a numeric value of type double.

Execution public double UserDao.* (double,..): matches the method whose first parameter is of type double,.. Matches any number of parameters of any type.

Execution public double UserDao.* (double,double): matches a method whose parameter type is double,double.

Merge pointcut expression

In AspectJ, pointcut expressions can be expressed through the operator & &, | |,! Put it together.

/ * * merge pointcut expression * in AspectJ, pointcut expression can be expressed through the operator & &, | |,! Put it together. * / @ Pointcut ("execution (* * .insert (..)) | | execution (* * .delete (..)") Public void insertDeleteJoinPoint () {} lets the notification access the details of the current connection point

You can declare a parameter of type JoinPoint in the notification method. Then you can access the link details. Such as method name and parameter value.

/ * declare that the method is a pre-notification: execute * / @ Before ("execution (public xyz.huning.spring4.aop.dao.User xyz.huning.spring4.aop.dao.impl.UserDao.insert (xyz.huning.spring4.aop.dao.User)") public void beforeInsert (JoinPoint joinPoint) {System.out.println ("--beforeInsert with joinPoint-") before the target method starts / / get method name String methodName = joinPoint.getSignature () .getName (); / get parameter values String args = Arrays.toString (joinPoint.getArgs ()); System.out.println ("Taget method:" + methodName); System.out.println ("Taget method args:" + args);} Post Notification

The post notification is executed after the join point completes, that is, when the join point returns a result or throws an exception, the following post notification records the termination of the method.

A section can include one or more notifications.

/ * declare that the method is a post-notification: execute after the target method starts (even if the target method execution exception occurs) * the target method execution result cannot be accessed in the post-notification * / @ After ("execution (public xyz.huning.spring4.aop.dao.User xyz.huning.spring4.aop.dao.impl.UserDao.insert (xyz.huning.spring4.aop.dao.User) ") public void afterInsert () {System.out.println ("-- afterInsert- ") } return notification

Post notification is executed regardless of whether the join point returns normally or throws an exception. If you only want to log when the connection point returns, you should use a return notification instead of a post notification. In the return notification, you can access the return value of the join point as long as you add the returning attribute to the @ AfterReturning annotation. The value of this property is the name of the parameter used to pass in the return value.

You must add a parameter with the same name to the signature of the notification method. At run time, Spring AOP passes the return value through this parameter. The original pointcut expression needs to appear in the pointcut attribute.

/ * declare that the method is a return notification: return after the normal end of the target method (no longer execute when the target method execution exception occurs) * return notification that you can access the execution result of the target method * / @ AfterReturning (value= "execution (* xyz.huning.spring4.aop.dao.impl.UserDao.query (..))", returning= "result") public void afterQueryReturning (JoinPoint joinPoint) Object result) {System.out.println ("--afterQueryReturning with joinPoint and result-") String methodName = joinPoint.getSignature (). GetName (); String args = Arrays.toString (joinPoint.getArgs ()); System.out.println ("Taget method:" + methodName); System.out.println ("Taget method args:" + args); System.out.println ("Taget method execute result:" + result);} exception notification

Exception notification is performed only when the join point throws an exception, the throwing attribute is added to the @ AfterThrowing annotation, and the exception thrown by the join point can also be accessed. Throwable is the superclass of all error and exception classes.

So any errors and exceptions can be caught in the exception notification method. If you are only interested in a particular exception type, you can declare the parameter as the parameter type of another exception. The notification is then executed only when an exception is thrown for this type and its subclasses.

/ * declare that the method is an exception notification: execute this method when an exception occurs in the target method * exception notification that the exception object in the target method can be accessed And you can specify that the notification code * / @ AfterThrowing (value= "execution (* xyz.huning.spring4.aop.dao.impl.UserDao.* (..)", throwing= "e") public void afterAllThrowing (JoinPoint joinPoint,Exception e) {System.out.println ("--afterAllThrowing with throwing-") is executed when a specific exception occurs System.out.println ("Taget method execute exception:" + e);} / * specifies that the notification code * / @ AfterThrowing (value= "execution (* xyz.huning.spring4.aop.dao.impl.UserDao.* (..)", throwing= "e") public void afterAllThrowing (JoinPoint joinPoint,NullPointerException e) {System.out.println ("--afterAllThrowing with NullPointerException-") is executed when a specific exception occurs. System.out.println ("Taget method execute exception:" + e);} surround notification

Surround notification is the most powerful of all notification types and has comprehensive control over the connection point. You can even control whether join points are executed. For surround notifications, the parameter type of the join point must be ProceedingJoinPoint.

It is a subinterface of JoinPoint and allows you to control when to execute and whether to execute join points. In the surround notification, you need to explicitly call the proceed () method of ProceedingJoinPoint to execute the proxied method. Forgetting to do so will cause the notification to be executed, but the target method will not be executed.

Note: the method that surrounds the notification needs to return the result after the target method is executed, that is, the return value of the call joinPoint.proceed (), otherwise a null pointer exception will occur.

/ * surround notification needs to carry parameters of type ProceedingJoinPoint * the whole process of surround notification is similar to that of dynamic agents: parameters of type ProceedingJoinPoint can determine whether to execute the target method * and the surrounding notification must have a return value. The return value is the return value of the target method * / @ Around ("execution (* xyz.huning.spring4.aop.dao.impl.UserDao.delete (..)") Public Object around (ProceedingJoinPoint pj) {Object result = null; String methodName = pj.getSignature (). GetName (); try {/ / pre-notification System.out.println ("The method:" + methodName + "pre-notification"); / / execute target method result = pj.proceed (); / / return notification System.out.println ("The method:" + methodName + "return notification") } catch (Throwable e) {/ / exception notification System.out.println ("The method:" + methodName + "exception notification:" + e.getMessage ());} / / post notification System.out.println ("The method:" + methodName + "post notification"); return result;} specifies the priority of the section

When more than one aspect is applied to the same join point, their priority is uncertain unless explicitly specified.

The priority of the aspect can be specified by implementing the Ordered interface or by using the @ Order annotation. To implement the Ordered interface, the smaller the return value of the getOrder () method, the higher the priority. If you use the @ Order annotation, the serial number appears in the comment.

Reuse pointcut definition

When writing AspectJ facets, you can write pointcut expressions directly in notification comments, but the same pointcut expression may be repeated in multiple notifications.

In the AspectJ aspect, you can declare a pointcut as a simple method through the @ Pointcut annotation. The method body of a pointcut is usually empty because it is unreasonable to mix the pointcut definition with the application logic.

The access control character of the pointcut method also controls the visibility of the pointcut. If pointcuts are to be shared across multiple aspects, it is best to centralize them in a common class. In this case, they must be declared as public.

When introducing this pointcut, you must include the class name. If the class is not in the same package as this aspect, it must also include the package name. Other notifications can introduce this pointcut through the method name.

/ * reuse pointcut expression * define a method for declaring pointcut expression In general, this method no longer needs to fill other code. * use @ Pointcut to declare pointcut expressions. * other notifications in the same class directly use the method name to refer to the current pointcut expression, for example: @ Before ("method ()") * notifications in other classes under the same report need to be preceded by the class name For example, @ Before ("class.method ()") * notifications in the classes under other packages need to be preceded by the fully qualified name of the class, such as @ AfterReturning (value= "package.class.method ()", returning= "result") * * the first asterisk represents matching any modifier and any return value, and the second asterisk indicates any method name. The two periods in the parameter list represent any number and type of parameter * / @ Pointcut ("execution (* xyz.huning.spring4.aop.dao.impl.UserDao.* (..)") Public void userDaoJoinPoint () {} on "how to use Spring to open annotations AOP support placement" this article shares here, 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, please 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