【问题标题】:@Async not working for me@Async 不适合我
【发布时间】:2011-05-02 22:07:50
【问题描述】:

我正在使用@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" />

谢谢。

【问题讨论】:

  • 您应该提供更多信息。 (代码 sn-ps 等)
  • 没有任何异常,它只是没有使方法异步。有什么特别的配置可以让它工作吗?这是我的问题,将发布我的配置以更多地了解我的环境。我的@Scheduled 已经可以正常工作了。

标签: java spring


【解决方案1】:

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

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

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

【讨论】:

  • 当然很容易错过。
【解决方案2】:

我遇到了类似的问题。我花了很多时间来修复它。

如果使用spring-context 3.2,还需要在调用方法服务的类上添加@EnableAsync注解@Async >

看看http://spring.io/guides/gs/async-method/#initial

希望对你有帮助。

【讨论】:

    【解决方案3】:

    这是对已接受答案的补充答案。您可以在自己的类中调用异步方法,但必须创建自引用 bean。

    这里唯一的副作用是您不能在构造函数中调用任何异步代码。这是将代码保存在同一个地方的好方法。

    @Autowired ApplicationContext appContext;
    private MyAutowiredService self;
    
    @PostConstruct
    private void init() {
        self = appContext.getBean(MyAutowiredService.class);
    }
    
    public void doService() {
        //This will invoke the async proxy code
        self.doAsync();
    }
    
    @Async 
    public void doAsync() {
        //Async logic here...
    }
    

    【讨论】:

      【解决方案4】:

      您可以在服务中使用@EnableAsync...

      【讨论】:

      • 您能否详细说明您的答案,为您提供的解决方案添加一些细节?
      • @alireza alallah : 请在答案中添加一些细节
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 2011-08-11
      • 2011-01-05
      • 2011-12-23
      • 2012-04-01
      • 2012-12-07
      • 2012-05-04
      相关资源
      最近更新 更多