2017-08-06 123 views
0

我正在使用Spring 3.2.2.RELEASE版本。 @Async詮釋不按預期工作。Spring @Async不起作用

的applicationContext.xml

<?xml version="1.0" encoding="windows-1252"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 


<!-- Enable AspectJ style of Spring AOP --> 
<aop:aspectj-autoproxy proxy-target-class="true"/> 



    <context:component-scan base-package="com.pratik" /> 



    <tx:annotation-driven /> 

import.java

public String async() { 
    final String asssetImportId = ObjectId.get().toHexString(); 

     process.asyncTest(); 

    logger.info("Ongoing"); 
    return asssetImportId; 
    } 

process.java

@Async 
    public void asyncTest() { 
    try { 
     Thread.sleep(1000); 

    } catch (InterruptedException e) { 

     e.printStackTrace(); 
    } 
    logger.info("After Sleep"); 

    } 

後睡眠日誌應打印最後卻是越來越打印持續

+0

'的Thread.sleep應爲(1000)',是這兩種方法同樣的類 –

+0

這裏有很多可能性,你沒有顯示開啓異步支持(你在Spring的一個過時的版本),你沒有顯示你從哪裏得到'process'變量。零時間 – chrylis

+0

@ @ Async'的使用要求您將'@ EnableAsync'註釋添加到其中一個'@ Configuration'類。 –

回答

0

了Thread.sleep(000)似乎是一個錯字到我面前。如果apo允許您進行0次睡眠,這將是打印在您預期之前發生的一個很好的原因(可能並非總是如此,因爲您在談論異步打印的任何「訂單」可能會發生)

編輯: tx:註解驅動用於事務性支持。添加背景:註解配置

EDIT2:更正:使用「任務:註解驅動的(不要與TX命名空間混淆)

+0

我更改了代碼並創建了Thread.sleep(5000)。它仍然像單線程模型一樣工作。 –

+0

你如何檢索「process」bean?您不顯示代碼的那部分 –

+0

進程bean是自動裝配的。我已經使用了spring @component anotation –