@ Async java Asynchronous Method, @ async asynchronous

Source: Internet
Author: User

@ Async java Asynchronous Method, @ async asynchronous

In spring 3, the @ Async annotation enables a method to be quickly converted to asynchronous execution, and immediately comes to the DEMO.

If you have registered a Website user, you need to send an email before the user can continue to work after receiving confirmation from the email;
Assume that sending is a very time-consuming process, so asynchronous transmission is required.

1 namespace Note: add the task

Java code
  1. <? Xml version = "1.0" encoding = "UTF-8"?>
  2. <Beans xmlns = "http://www.springframework.org/schema/beans” xmlns: xsi =" http://www.w3.org/2001/XMLSchema-instance"
  3. Xmlns: p = "http://www.springframework.org/schema/p” xmlns: context =" http://www.springframework.org/schema/context"
  4. Xsi: schemaLocation ="
  5. Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  6. Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
  7. Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
  8. <Context: component-scan base-package = "cs"/>
  9. </Beans>



2 RegularService. java registration class

Java code
    1. Import org. springframework. beans. factory. annotation. Autowired;
    2. Import org. springframework. stereotype. Service;
    3. Import cs. async. MailUtility;
    4. @ Service
    5. Public class RegularService {
    6. @ Autowired
    7. Private MailUtility mailUtility;
    8. Public void registerUser (String userName ){
    9. System. out. println ("User registration for" + userName + "complete ");
    10. MailUtility. sendMail (userName );
    11. System. out. println ("registration is complete, mail is sent later");
    12. }
    13. }
    14. 3 tools for sending emails
    15. <Pre name = "code" class = "java"> import org. springframework. scheduling. annotation. Async;
    16. Import org. springframework. stereotype. Component;
    17. @ Component
    18. Public class MailUtility {
    19. @ Async
    20. Public void sendMail (String name ){
    21. System. out. println ("Preparing for sending");
    22. Try {
    23. Thread. sleep (5000 );
    24. } Catch (InterruptedException e ){
    25. E. printStackTrace ();
    26. }
    27. System. out. println ("Asynchronous Transmission completed");
    28. }
    29. }
    30. </Pre>
    31. <Br>
    32. <Br> 4 Add the following in applicationContext. xml:
    33. <Br> <pre name = "code" class = "java"> <? Xml version = "1.0" encoding = "UTF-8"?>
    34. <Beans xmlns = "http://www.springframework.org/schema/beans” xmlns: xsi =" http://www.w3.org/2001/XMLSchema-instance"
    35. Xmlns: p = "http://www.springframework.org/schema/p” xmlns: context =" http://www.springframework.org/schema/context"
    36. Xmlns: task = "http://www.springframework.org/schema/task"
    37. Xsi: schemaLocation ="
    38. Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    39. Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    40. Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
    41. <Context: component-scan base-package = "cs"/>
    42. <Task: annotation-driven/>
    43. </Beans>
    44. </Pre>
    45. <Br> it must be <task: annotation-driven/>.
    46. <Br>
    47. <Br> 5 run:
    48. <Br> User registration for tom complete
    49. <Br> the registration is complete and the email will be sent later.
    50. <Br> preparing for sending
    51. <Br> asynchronous transmission is complete.
    52. <Br>
    53. <Br> 6. Sometimes, return values from the asynchronous method. At this time, spring will return a java. util. concurrent. Future object and call the get method, for example
    54. <Br> <pre name = "code" class = "java"> @ Async
    55. Public Future <Balance> findBalanceAsync (final Account account ){
    56. Balance balance = accountRepository. findBalance (account );
    57. Return new AsyncResult <Balance> (balance );
    58. }
    59. Balance balance = future. get ();
    60. </Pre>
    61. <Br>
    62. <Br>
    63. Note: Circular dependency must be resolved.
    64. Principle: spring scans beans to check whether @ async annotations are included in the method. If any annotation is included, spring dynamically generates a subclass for the bean, we call it a proxy class (?), The proxy class inherits the bean we wrote and injects the proxy class into it. At this time, when this method is executed, it will be in the proxy class. The proxy class determines that this method needs to be executed asynchronously, it will not call the corresponding method of the parent class (the bean we originally wrote. Spring maintains a queue by itself. It puts the methods to be executed into the queue, waits for the thread pool to read the queue, completes method execution, and completes asynchronous functions.
    65. Solve the cycle dependency caused by spring @ Async

      Today, the project (spring3.0.6 + structs2.2.3) is reduced. The business layer beans are all annotated with @ Service, and the set injection is replaced with @ Autowired. All the business bean configurations are cleared from the xml configuration file.
      In this case, the bean reporting loop dependency (reference) that specifically handles asynchronous operations is as follows ):
      Bean with name '********** 'has been injected into other beans [******,**********, **********, * ********] in its raw version as part of a circular reference beanA injection is used for asynchronous processing of beanB (Methods containing @ Async annotations ), beanB injects beanA to Implement Asynchronous processing.
      Solution: beanC (excluding @ Async annotation) is the beanB proxy service for beanA injection asynchronous processing. beanC injects beanB for processing.

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.