ASPECTJ annotation configuration for Spring AOP instances

Source: Internet
Author: User

http://blog.csdn.net/xiaoxian8023/article/details/17285809

The XML configuration of the spring AOP instance is explained in the previous blog post, which explains how to configure Spring AOP by ASPECTJ annotations today.

The JDK proxy, interface and implementation class code are still used, please refer to the previous blog post. The main is to share the aspect class:

[Java]View Plaincopy
  1. Package COM.TGB.AOP;
  2. Import Org.aspectj.lang.JoinPoint;
  3. Import Org.aspectj.lang.ProceedingJoinPoint;
  4. Import Org.aspectj.lang.annotation.After;
  5. Import org.aspectj.lang.annotation.AfterReturning;
  6. Import org.aspectj.lang.annotation.AfterThrowing;
  7. Import Org.aspectj.lang.annotation.Around;
  8. Import Org.aspectj.lang.annotation.Aspect;
  9. Import Org.aspectj.lang.annotation.Before;
  10. Import org.aspectj.lang.annotation.DeclareParents;
  11. Import Org.aspectj.lang.annotation.Pointcut;
  12. /**
  13. * Test after,before,around,throwing,returning Advice.
  14. * @author Admin
  15. *
  16. */
  17. @Aspect
  18. Public class Aspcejadvice {
  19. /** 
  20. * Pointcut
  21. * The name of the definition pointcut,pointcut is Aspectjmethod (), this method has no return value and parameter
  22. * The method is an identity, not a call
  23. */
  24. @Pointcut ("Execution (* find* (..))")
  25. private void Aspectjmethod () {};
  26. /**  
  27. * Before
  28. * Execution before core business execution, cannot prevent the call of core business.
  29. * @param joinpoint
  30. */
  31. @Before ("Aspectjmethod ()")
  32. public void Beforeadvice (Joinpoint joinpoint) {
  33. System.out.println ("-----beforeadvice (). Invoke-----");
  34. System.out.println ("Do some security judgments and so on before executing the core business logic");
  35. System.out.println ("Can get what you need through Joinpoint");
  36. System.out.println ("-----End of Beforeadvice ()------");
  37. }
  38. /**  
  39. * After
  40. * After the core business logic exits (including normal execution end and abnormal exit), perform this advice
  41. * @param joinpoint
  42. */
  43. @After (value = "Aspectjmethod ()")
  44. public void Afteradvice (Joinpoint joinpoint) {
  45. System.out.println ("-----afteradvice (). Invoke-----");
  46. System.out.println ("Do some logging operations and so on after executing the core business logic");
  47. System.out.println ("Can get what you need through Joinpoint");
  48. System.out.println ("-----End of Afteradvice ()------");
  49. }
  50. /**  
  51. * Around
  52. * Manual control calls the core business logic, as well as pre-and post-call processing,
  53. *
  54. * Note: When the core business throws an exception, exit immediately and turn to Afteradvice
  55. * Finish Afteradvice, then go to Throwingadvice
  56. * @param PJP
  57. * @return
  58. * @throws Throwable
  59. */
  60. @Around (value = "Aspectjmethod ()")
  61. Public Object Aroundadvice (proceedingjoinpoint pjp) throws Throwable {
  62. System.out.println ("-----aroundadvice (). Invoke-----");
  63. System.out.println ("Things like before advice can be done here");
  64. //Call Core Logic
  65. Object RetVal = Pjp.proceed ();
  66. System.out.println ("Things like after advice" can be done here);
  67. System.out.println ("-----End of Aroundadvice ()------");
  68. return retVal;
  69. }
  70. /**  
  71. * afterreturning
  72. * Core business logic call after normal exit, regardless of whether there is a return value, after normal exit, do this advice
  73. * @param joinpoint
  74. */
  75. @AfterReturning (value = "Aspectjmethod ()", returning = "RetVal")
  76. public void Afterreturningadvice (Joinpoint joinpoint, String retVal) {
  77. System.out.println ("-----afterreturningadvice (). Invoke-----");
  78. System.out.println ("Return Value:" + retVal);
  79. System.out.println ("The return value can be further processed here");
  80. System.out.println ("Can get what you need through Joinpoint");
  81. System.out.println ("-----End of Afterreturningadvice ()------");
  82. }
  83. /** 
  84. * Core business logic call after exception exit, execute this advice, handle error message
  85. *
  86. * Note: Execution sequence after around advice
  87. * @param joinpoint
  88. * @param ex
  89. */
  90. @AfterThrowing (value = "Aspectjmethod ()", throwing = "ex")
  91. public void Afterthrowingadvice (Joinpoint joinpoint, Exception ex) {
  92. System.out.println ("-----afterthrowingadvice (). Invoke-----");
  93. SYSTEM.OUT.PRINTLN ("error message:" +ex.getmessage ());
  94. System.out.println ("Here is intended to perform core business logic errors, catch exceptions, and can do some logging operations, etc.");
  95. System.out.println ("Can get what you need through Joinpoint");
  96. System.out.println ("-----End of Afterthrowingadvice ()------");
  97. }
  98. }



In Application-config.xml, you only need to configure the business logic bean and the aspect bean, and enable aspect annotations:

    1. <? XML version= "1.0" encoding="UTF-8"?>
    2. <beans xmlns="Http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:aop="HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
    5. xmlns:tx="Http://www.springframework.org/schema/tx"
    6. xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans /spring-beans-2.0.xsd
    7. HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    8. Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd ">
    9. <!--enable ASPECTJ support for annotation-
    10. <aop:aspectj-autoproxy/>
    11. <Bean id= "usermanager" class="Com.tgb.aop.UserManagerImpl"/>
    12. <Bean id= "aspcejhandler" class="Com.tgb.aop.AspceJAdvice"/>
    13. </Beans>

The order in which the Aroundadvice, Beforeadvice, Afteradvice, Returningadvice are executed is determined by the order of the annotations. But sometimes the order is changed, and the result is not changed, possibly because of the cache. I had this problem a few days ago, but I tested it again today and found that the order of execution was consistent with the order of the annotations.

Both XML and Annotation annotations can be configured as configuration items to manage Spring AOP, so what are the pros and cons of each?

First, talk about XML. XML is almost always used as a configuration item in Web applications, such as the framework Struts, Spring, Hibernate, and so on, which are used as configurations. XML is so popular because many of its advantages are irreplaceable in the configuration of other technologies:

      • The biggest advantage of XML as an Extensible Markup language is that developers can tailor the applicable markup to the software to make the code more understandable.
      • The use of XML configuration can make the software more extensible. Spring, for example, configures dependencies between classes in XML to maximize the scalability of the application.
      • Proven validation mechanism to ensure program correctness. Using a Schema or DTD, you can validate the correctness of the XML and avoid an illegal configuration that results in an application error.
      • Modify the configuration without changing the existing program.

Although there are so many advantages, but after all, there is no omnipotent thing, XML has its own shortcomings.

      • Support for parsing tools or class libraries is required.
      • Parsing XML is bound to affect application performance and consume system resources.
      • Too many profiles cause management to become difficult.
      • The compilation period cannot validate the correctness of its configuration items, or the error can only be run during runtime.
      • The IDE cannot verify the correctness of the configuration items.
      • It becomes difficult to find fault. Often the configuration of a hand mistakenly leads to inexplicable errors.
      • Developers have to maintain code and configuration files at the same time, and development inefficiencies become inefficient.
      • There are unspoken rules between the configuration item and the code. Change either party may affect the other party.

Let's look at the advantages of Annotation.

      • Save in the class file to reduce maintenance costs.
      • No tooling support, no parsing required.
      • Compile time to verify correctness, error checking becomes easy.
      • Improve development efficiency.

The same Annotation is not omnipotent, it also has a lot of shortcomings.

      • To modify a configuration item, you have to modify the Java file to recompile the packaged app.
      • The configuration item is encoded in a Java file, which is poor extensibility.

Summary: No one thing is omnipotent, the same XML and Java Annotation have their own advantages and disadvantages. By contrast, careful readers may have found that their strengths and weaknesses are complementary. The strength of XML is not Annotation, and Annotation's advantage is the lack of XML. This is why the current popular XML + Annotation configuration. Balance is the kingly way!

ASPECTJ annotation configuration for Spring AOP instances

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.