@异步对我不起作用


问题内容

我正在使用@Scheduled,它一直工作正常,但无法使@Async工作。我对其进行了多次测试,似乎它使我的方法变得异步。我还有其他东西,配置或参数吗?我有一个类有两个方法,一个是标有@Scheduled的方法,它执行并调用第二个标有@Async的方法。

这是我的配置:

<!-- Scans within the base package of the application for @Components to configure as beans -->
<context:component-scan base-package="com.socialmeety" />
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager" />
<task:annotation-driven/>

<!-- Configures support for @Controllers -->
<mvc:annotation-driven />

<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<dwr:configuration />
<dwr:annotation-config />
<dwr:url-mapping />
<dwr:controller id="dwrController" debug="true" />

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />

谢谢。


问题答案:

当您从同一对象中的另一个方法调用@Async方法时,您可能会绕过异步代理代码,而只是调用您的普通方法,即在同一线程中。

解决此问题的一种方法是,确保对@Async方法的调用来自另一个对象。请参阅本文结尾处的评论:http :
//groovyjavathoughts.blogspot.com/2010/01/asynchronous-code-with-
spring-3-simple.html

但是这样做很麻烦,因此您可以自动连接TaskScheduler,将方法包装在Runnable中并自己执行。