SPRINGMVC two ways to configure AOP

Source: Internet
Author: User

Spingmvc There are two ways to configure AOP, one is to configure with annotations, and the other is to implement an XML configuration.

To apply annotations in a way that configures:

Introduce the dependencies that AOP uses in MAVEN first

<dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-aop< /artifactid>      <version>4.3.1.RELEASE</version>    </dependency>    <!--AOP Aspect Commentary guide    <dependency>      <groupId>org.aspectj</groupId>      <artifactId> aspectjrt</artifactid>      <version>1.8.6</version>    </dependency>    < dependency>      <groupId>org.aspectj</groupId>      <artifactid>aspectjweaver</ artifactid>      <version>1.8.9</version>    </dependency>

The AOP configuration is then included in the Springmvc configuration file, which scans the AOP packages and lets AOP take effect

<!--AOP annotations; define aspect-    -<!--activate component scanning to automatically scan components configured with annotations under package "COM.EXAMPLE.AOP and its sub-packages--    <context: Component-scan base-package = "Com.example.aop"/>    <!--start ASPECTJ support   is only valid    for scanned beans-- <aop:aspectj-autoproxy proxy-target-Class= "true"/>

Then join the AOP logic processing class

 PackageCOM.EXAMPLE.AOP;Importjava.util.Arrays;Importjava.util.List;ImportOrg.aspectj.lang.JoinPoint;ImportOrg.aspectj.lang.ProceedingJoinPoint;ImportOrg.aspectj.lang.annotation.After;Importorg.aspectj.lang.annotation.AfterReturning;Importorg.aspectj.lang.annotation.AfterThrowing;ImportOrg.aspectj.lang.annotation.Around;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.aspectj.lang.annotation.Before;ImportOrg.aspectj.lang.annotation.Pointcut;ImportOrg.springframework.core.annotation.Order;Importorg.springframework.stereotype.Component; @Aspect//the label declares the Loggeraspect class as a slice@Order (1)//set the priority of a slice: if there are multiple facets, you can control the order in which the slices are executed by setting the priority (the smaller the number, the higher the priority)@Component//This tag puts the Loggeraspect class in the IOC container Public classLoggeraspect {/*** Define a method that declares a pointcut expression, which generally does not require adding additional code * Use @pointcut to declare the notification immediately after the pointcut expression * to refer to the current pointcut expression directly using the method name, and if other classes are used, add the package name 
    */@Pointcut ("Execution (Public * com.example.controller.*controller.* (..))")     Public voiddeclearjoinpointexpression () {}/*** PRE-notification *@paramJoinpoint*/@Before ("Declearjoinpointexpression ()")//the label declares that the secondary method is a pre-notification: Executes before the target method starts     Public voidBeformethod (Joinpoint joinpoint) {String methodName=joinpoint.getsignature (). GetName (); List<Object> args =arrays.aslist (Joinpoint.getargs ()); System.out.println ("This method" +methodname+ "begin." param< "+ args+" > "); }    /*** Post notification (does not access the return value of the method, regardless of whether the method has an exception) *@paramJoinpoint*/@After ("Declearjoinpointexpression ()")     Public voidAftermethod (Joinpoint joinpoint) {String methodName=joinpoint.getsignature (). GetName (); System.out.println ("This method" +methodname+ "end."); }    /*** Return notification (code executed at normal end of method) * Return notification can access the return value of the method! * @paramJoinpoint*/@AfterReturning (Value= "Declearjoinpointexpression ()", returning= "result")     Public voidAfterreturnmethod (joinpoint joinpoint,object result) {String methodName=joinpoint.getsignature (). GetName (); System.out.println ("This method" +methodname+ "end.result<" +result+ ">"); }    /*** Exception Notification (code for method exception execution) * can access the exception object, and can specify code to execute when a specific exception occurs *@paramJoinpoint *@paramex*/@AfterThrowing (Value= "Declearjoinpointexpression ()", throwing= "ex")     Public voidAfterthrowingmethod (Joinpoint joinpoint,exception ex) {String methodName=joinpoint.getsignature (). GetName (); System.out.println ("This method" +methodname+ "End.ex message<" +ex+ ">"); }    /*** Surround notification (need to carry a parameter of type Proceedingjoinpoint type) * Surround notification contains front, back, return, exception notification, proceedingjoinpoin type parameter can decide whether to execute the target method * and surround Pass Must have a return value, which is the return value of the target method *@param Point*/@Around (Value= "Declearjoinpointexpression ()")     PublicObject Aroundmethod (Proceedingjoinpoint point) {object result=NULL; String MethodName=point.getsignature (). GetName (); Try {            //front-facing notificationsSystem.out.println ("the method" + methodname+ "start. param< "+ arrays.aslist (Point.getargs ()) +" > "); //Execute target Methodresult =point.proceed (); //Back to NotificationsSystem.out.println ("the method" + methodname+ "end. result< "+ result+" > "); } Catch(Throwable e) {//Exception NotificationSystem.out.println ("This method" +methodname+ "End.ex message<" +e+ ">"); Throw NewRuntimeException (e); }        //Post NotificationSystem.out.println ("the method" + methodname+ "end.")); returnresult; }}

Add annotations to the class aspect declaration This class is a facet, plus the component annotation is added to the IOC container. The order note is a priority, if only one slice class can be used. Annotation Pointcut is the scope for declaring annotations. Execution (Public * com.example.controller.*controller.* (..)) I use the execution expression here, representing the function Com.example.controller all the public methods that end the class with the controller. There is usually no need for content in the methods described @pointcut. The slice notification contains:

Pre-notification (@Before, the parameter is Joinpoint before executing the method)

The post notification (@After, regardless of whether the method throws an exception is executed, so the return value of the method is not obtained. parameter is Joinpoint)

Returns the notification (@AfterReturning, which executes after the method has completed gracefully, and can get the return value of the method. Parameters are Joinpoint and result (Object))

Exception notification (@AfterThrowing, executed when the method throws an exception, you can get to the exception object, and you can specify the code to execute when a particular exception occurs, with the parameter Joinpoint exception)

Surround notifications (@Around, surround notifications need to carry the type Proceedingjoinpoint type parameters, surround notification contains the front, back, return, exception notification, Proceedingjoinpoin type parameters can decide whether to execute the target method, and the surround notification must have a return value, which is the return value of the target method)

Apply an XML-mode configuration

Dependency, you should not include the dependency on AOP annotations. First define a class as the slice class.

 PackageCOM.EXAMPLE.AOP;Importjava.util.Arrays;Importjava.util.List;ImportOrg.aspectj.lang.JoinPoint;ImportOrg.aspectj.lang.ProceedingJoinPoint;Importorg.springframework.stereotype.Component; @Component//This tag puts the Loggeraspect class in the IOC container Public classSysaspect {/*** PRE-notification *@paramJoinpoint*/     Public voidBeformethod (Joinpoint joinpoint) {String methodName=joinpoint.getsignature (). GetName (); List<Object> args =arrays.aslist (Joinpoint.getargs ()); System.out.println ("This method" +methodname+ "begin." param< "+ args+" > "); }    /*** Post notification (does not access the return value of the method, regardless of whether the method has an exception) *@paramJoinpoint*/     Public voidAftermethod (Joinpoint joinpoint) {String methodName=joinpoint.getsignature (). GetName (); System.out.println ("This method" +methodname+ "end."); }    /*** Return notification (code executed at normal end of method) * Return notification can access the return value of the method! * @paramJoinpoint*/     Public voidAfterreturnmethod (joinpoint joinpoint,object result) {String methodName=joinpoint.getsignature (). GetName (); System.out.println ("This method" +methodname+ "end.result<" +result+ ">"); }    /*** Exception Notification (code for method exception execution) * can access the exception object, and can specify code to execute when a specific exception occurs *@paramJoinpoint *@paramex*/     Public voidAfterthrowingmethod (Joinpoint joinpoint,exception ex) {String methodName=joinpoint.getsignature (). GetName (); System.out.println ("This method" +methodname+ "End.ex message<" +ex+ ">"); }    /*** Surround notification (need to carry a parameter of type Proceedingjoinpoint type) * Surround notification contains front, back, return, exception notification, proceedingjoinpoin type parameter can decide whether to execute the target method * and surround Pass Must have a return value, which is the return value of the target method *@param Point*/     PublicObject Aroundmethod (Proceedingjoinpoint point) {object result=NULL; String MethodName=point.getsignature (). GetName (); Try {            //front-facing notificationsSystem.out.println ("the method" + methodname+ "start. param< "+ arrays.aslist (Point.getargs ()) +" > "); //Execute target Methodresult =point.proceed (); //Back to NotificationsSystem.out.println ("the method" + methodname+ "end. result< "+ result+" > "); } Catch(Throwable e) {//Exception NotificationSystem.out.println ("This method" +methodname+ "End.ex message<" +e+ ">"); Throw NewRuntimeException (e); }        //Post NotificationSystem.out.println ("the method" + methodname+ "end.")); returnresult; }}

As you can see, this class does not differ from the normal AOP tangent class except for the annotations of @aspect and related facets. If you declare it to be a slice. We need to configure it manually in the XML file.

<!--bean-to-<bean id= "sysaspect" configuration facetsclass= "Com.example.aop.SysAspect"/> <!--configuring AOP--<aop:config> <!--configuring pointcut expressions--< Aop:pointcut id= "pointcut" expression= "Execution (public * com.example.controller.*controller.* (..))"            /> <!--configuration facets and configuration--<aop:aspect order= "3" ref= "Sysaspect" > <!--Front Notification-- <aop:before method= "Beformethod" pointcut-ref= "Pointcut"/> <!--post Notification--<a Op:after method= "Aftermethod" pointcut-ref= "Pointcut"/> <!--back to notifications-<aop:after-return ing method= "afterreturnmethod" pointcut-ref= "pointcut" returning= "result"/> <!--exception Notification---& Lt;aop:after-throwing method= "Afterthrowingmethod" pointcut-ref= "Pointcut" throwing= "ex"/> <aop:around me Thod= "Aroundmethod" pointcut-ref= "Pointcut"/> </aop:aspect> </aop:config>

The defined slice bean is our custom slice class, and then we configure AOP (<aop:config>). Define the slice range pointcut first. The rest is the development of AOP's slice class, priority, and then detailed configuration of the slices ' notifications. This is consistent with the way the annotations are produced.

SPRINGMVC two ways to configure AOP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.