Spring AOP Application

Source: Internet
Author: User
Tags modifiers throwable

Transferred from: http://wb284551926.iteye.com/blog/1887650

Recently the new project to start, in the construction of the project infrastructure, want to join the log function and performance monitoring functions, think of a lot of ideas, and finally think of using spring's AOP function, one is not to write so many duplicate code, the second is flexible and easy to use, OK now talk about this AOP feature usage. (Required jar Packages: Spring.jar, Asm-2.2.3.jar, Asm-commons-2.2.3.jar, Aopalliance.jar, Aspectjweaver.jar, cglib-nodep-2.1_3.) Jar, can ignore version number)

1. Establish a cut-in class, including Dobefore, Doaround, Doafter, Dothrowing and other methods.

Java code
  1. /*****************************************
  2. * @ Class Name: Com.util.TestAspect
  3. * @ Wang Bo
  4. * @ time: June 15, 2013
  5. * @ Version: 1.0
  6. * Description:
  7. * @ Modify People:
  8. * @ Modified Time:
  9. * @ Modify Description:
  10. *****************************************/
  11. Package com.util;
  12. Import Org.aspectj.lang.JoinPoint;
  13. Import Org.aspectj.lang.ProceedingJoinPoint;
  14. Public class Testaspect {
  15. public void Doafter (Joinpoint jp) {
  16. SYSTEM.OUT.PRINTLN ("Log ending method:"
  17. + Jp.gettarget (). GetClass (). GetName () + "."
  18. + jp.getsignature (). GetName ());
  19. }
  20. Public Object Doaround (proceedingjoinpoint pjp) throws Throwable {
  21. Long time = System.currenttimemillis ();
  22. Object RetVal = Pjp.proceed ();
  23. Time = System.currenttimemillis ()-time;
  24. SYSTEM.OUT.PRINTLN ("Process time:" + Time + "MS");
  25. return retVal;
  26. }
  27. public void Dobefore (Joinpoint jp) {
  28. SYSTEM.OUT.PRINTLN ("Log begining method:"
  29. + Jp.gettarget (). GetClass (). GetName () + "."
  30. + jp.getsignature (). GetName ());
  31. }
  32. public void dothrowing (Joinpoint JP, Throwable ex) {
  33. System.out.println ("method" + jp.gettarget (). GetClass (). GetName ()
  34. + "." + jp.getsignature (). GetName () + "throw exception");
  35. System.out.println (Ex.getmessage ());
  36. }
  37. }

2. Add the AOP configuration to the spring configuration file, proxy-target-class= "true" red part * Note *, do not add this, action is not intercepted, remember

Com.neau.project.*.*.*.* (..)) " The main attention here is

For example, your package structure is com.xxx.action.actionclass you need to write this to intercept com.xxx.action.actionclass.*.

The last. * is the method represented in Actionclass. Here is a detailed description of this configuration

If you want to release some methods, such as the Get/set method, you can use the and keyword, for example

Execution (* com.neau.project.*.*.*.* (..)) and!execution (* com.neau.project.*.*.*.get* (..)) and!execution (* com.neau.project.*.*.*.set* (..))

XML code
  1. <aop:config <span style="color: #ff0000;" >proxy-target-class="true"> </span>
  2. <aop:aspect id="Testaspect" ref="Aspectbean">
  3. <!--Configure all methods for all classes or interfaces under the Com.neau.project.*.*.*.* package--
  4. <aop:pointcut id="Aopservice"
  5.                 expression= "Execution (* <span  style= "color:  #ff0000;" >com.neau.project.*.*.*.*</span > (..)) "  />               <aop:before pointcut-ref= "Aopservice"  method= " Dobefore "/>    
  6. <aop:after pointcut-ref="Aopservice" method="Doafter"/>
  7. <aop:around pointcut-ref="Aopservice" method="Doaround"/>
  8. <aop:after-throwing pointcut-ref="Aopservice" method="dothrowing" throwing= "ex "/>
  9. </aop:aspect>
  10. </aop:config>
  11. <Bean id= "aspectbean" class="Com.util.TestAspect" />

3. Start the project and execute

Access action

Java code
  1. Log begining Method:com.neau.project.logon.action.LogonAction.test
  2. 2013-06-: $,737-{pstm-100001} executing statement:select count (*) from RDTT EAM t
  3. 2013-06-: $,737-{pstm-100001} Parameters: []
  4. 2013-06-: $,737-{pstm-100001} Types: []
  5. 2013-06-: ,749-{pstm-100004} executing statement:select t.* from Rdtteam t Limi     T??
  6. 2013-06-: 749-{pstm-100004} Parameters: [0 ] /c15>
  7. 2013-06-: 749-{pstm-100004} Types: [Java.lang.Integer, Java.lang.Integer]
  8. Log ending Method:com.neau.project.logon.action.LogonAction.test
  9. Process time: 261 ms
  10. Log begining Method:com.neau.project.logon.action.LogonAction.getRdtTeamPage
  11. Log ending Method:com.neau.project.logon.action.LogonAction.getRdtTeamPage
  12. Process time: 0 ms
  13. Log begining Method:com.neau.project.logon.action.LogonAction.get_rdtTeamList
  14. Log ending Method:com.neau.project.logon.action.LogonAction.get_rdtTeamList
  15. Process time: 0 ms

AOP is the way to achieve the interception action, simple, simple work to achieve big function is I wait for the developer's goal.

Steal something else and write it.

The Spring reference manual defines the following important concepts of AOP, which are analyzed in conjunction with the above code:

  • Aspect (Aspect): The official abstraction is defined as "a focus of modularity, this concern may be crosscutting multiple objects", in this case, "tangent" is the specific behavior of the class Testaspect, for example, Aserviceimpl.bara () Call is one of the behaviors that the tangent testaspect is concerned about. "Slices" are configured in the ApplicationContext <aop:aspect>.
  • Connection point (Joinpoint): A behavior such as a call to Aserviceimpl.bara () or Bserviceimpl.barb (String _msg, int _type) to throw an exception during the execution of a program.
  • Notification (Advice): The action that "slice" produces for a "connection point", for example, the action of logging the methods of all classes under the Com.spring.service package in Testaspect is a Advice. Where a "slice" can contain multiple "Advice", such as Testaspect
  • Pointcut (Pointcut): an assertion that matches a connection point, a notification in AOP, and a Pointcut expression association. For example, all the notifications in Testaspect are concerned with connection points that are execution by pointcut expressions (* com.spring.service.*.* (..)) To decide
  • Target object: An object that is notified by one or more facets. For example, Aservcieimpl and Bserviceimpl, of course, when actually running, Spring AOP takes the proxy implementation, the actual AOP operation is TargetObject proxy object.
  • AOP Proxy (AOP proxies) has two kinds of proxy methods in spring AOP, JDK dynamic agent and cglib agent. By default, when the TargetObject implements an interface, the JDK dynamic agent is used, for example, Aserviceimpl; Conversely, cglib proxies, for example, Bserviceimpl. Force the use of the Cglib proxy to <aop:config> proxy-target-class set the property to True

Notification (Advice) type

    • Pre-notification (before advice): A notification that is performed before a connection point (Joinpoint), but this notification does not prevent execution before the connection point. The ApplicationContext uses <aop:before> elements to declare in <aop:aspect>. For example, the Dobefore method in Testaspect
    • Post notification (after advice): A notification that is executed when a connection point exits (whether it is a normal return or an unexpected exit). The ApplicationContext uses <aop:after> elements to declare in <aop:aspect>. For example, the Doafter method in Testaspect, so when Bserviceimpl.barb throws an exception in Aoptest, the Doafter method still executes
    • After return notification (after return advice): A notification that is executed after a connection point is completed normally, excluding the case of throwing an exception. The ApplicationContext uses <after-returning> elements to declare in <aop:aspect>.
    • Surround notification (Around advice): A notification that surrounds a connection point, similar to the Dofilter method of the filter in the servlet specification in the Web. You can customize the behavior before and after the call to the method, or you can choose not to execute. The ApplicationContext uses <aop:around> elements to declare in <aop:aspect>. For example, the Doaround method in Testaspect.
    • Notification after an exception is thrown (after throwing advice): the notification that is executed when the method throws an exception exits. The ApplicationContext uses <aop:after-throwing> elements to declare in <aop:aspect>. For example, the Dothrowing method in Testaspect.

Pointcut expression

    • In general, the use of "execution" in an expression can satisfy most of the requirements. The expression format is as follows:
Java code
    1. Execution (Modifiers-pattern ret-type-pattern declaring-type-pattern? Name-pattern (Param-pattern)   Throws-pattern?)

Modifiers-pattern: Operation Permissions for methods

Ret-type-pattern: Return value

Declaring-type-pattern: The package where the method resides

Name-pattern: Method Name

Parm-pattern: Name of parameter

Throws-pattern: Exception

Among them, other than Ret-type-pattern and Name-pattern, the others are optional. In the example above, execution (* com.spring.service.*.* (..)) Represents the Com.spring.service package, the return value is any type, the method name is arbitrary, the parameters are not limited to all methods.

    • Notification parameters

Parameters can be bound by args so that the specific parameters can be accessed in the notification (Advice). For example,,<aop:aspect> is configured as follows

Java code
    1. <aop:config>  
    2.     <aop:aspect id=< Span class= "string" "Testaspect"  ref= "Aspectbean" >&NBSP;&NBSP;
    3.         <aop:pointcut id= " Businessservice "&NBSP;&NBSP;
    4.              expression= "Execution (* com.spring.service.*.* (string,..))  and args (msg,..) "  />  
    5.              <aop:after pointcut-ref= "Businessservice"  method= "Doafter"/>&NBSP;&NBSP;
    6.     </aop:aspect>  
    7. </aop:config>  

The MSG parameter can be accessed in the Testaspect Doafter method, but the Bserviceimpl () in Bara () and Barb in Aservice is no longer a connection point since execution (* Com.spring.service.*.* (String,..)) Only a method with the first parameter of type string is configured. Where the Doafter method is defined as follows:

Java code
    1. Public void Doafter (Joinpoint jp,string msg)
    • Access the current connection point

Any notification (Advice) method can define the first parameter as a org.aspectj.lang.JoinPoint type. The JoinPoint interface provides a number of useful methods, such as getArgs() (returning a method parameter), (returning a getThis() proxy object), (returning a getTarget() target), getSignature() (returning information about the method being notified), and toString() (printing out useful information about the method being notified).

Warning no match for this type name:com.zrm.service [Xlint:invalidabsolutetypename]

<aop:config>
<!--entry Point--
<aop:pointcut id= "gkservicepct" expression= "Execution (* com.zrm.service.* (..))"/>
<aop:advisor pointcut-ref= "gkservicepct" advice-ref= "Gktxadvice" order= "0"/>
</aop:config>

The warning no match for this type Name:com.zrm.service [Xlint:invalidabsolutetypename] Error appears

When configuring transactions, be sure to note that expression= "Execution (* com.zrm.service.* (..))" should be

expression= "Execution (* com.zrm.service.*.* (..))" so that the tangent point is anchored to the method.

Thank you: http://pandonix.iteye.com/blog/336873

Thank you: http://hi.baidu.com/gglzf4/item/a58624e2f962d113585dd832

Thank you: Comrade http://bbs.csdn.net/topics/350180595 on the 11 floor

Thank you: http://blog.sina.com.cn/s/blog_5f53615f0101ijdl.html

See so children's shoes experience let me take a lot of detours, it seems I just eat Baijia grow up child paper life, hurt AH. Hard-pressed developers can't afford to hurt themselves.

Spring AOP Application

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.