加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何使用spring异步运行方法?

发布时间:2020-12-14 05:57:03 所属栏目:Java 来源:网络整理
导读:下面的代码假设是异步工作,而是等待Async部分完成然后继续.如何使blah()方法异步运行? spring.xml ?xml version="1.0" encoding="UTF-8"?beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
下面的代码假设是异步工作,而是等待Async部分完成然后继续.如何使blah()方法异步运行?

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">

    <!-- Activates @Scheduled and @Async annotations for scheduling -->  
    <task:annotation-driven />

    <bean id="test"
        class="com.spring.test.Test">
</beans>

Test.java

@Path("/test")
public class Test
{
  @GET
  @Path("/test")
  @Produces("text/plain")
  public String tester()
  {
    return "Running...";
  }

  @GET
  @Path("/triggerNew")
  @Produces("text/plain")
  public String triggerNew()
  {
    System.out.println("BEFORE " + new Date() + " BEFORE");

    new Process().blah();

    System.out.println("AFTER " + new Date() + " AFTER");
    return "TRIGGERED";
  }
}

Process.java

@Component
    public class Process
    {
      @Async
      public void blah()
      {
        try
        {
          Thread.currentThread().sleep(5000);
        }
        catch (InterruptedException e)
        {
          e.printStackTrace(); 
        }
        System.out.println("NEW THREAD " + new Date() + " NEW THREAD");
      }
    }

解决方法

@Async仅在注释Spring管理的bean而不是任意类时才有效.您需要将Process定义为Spring bean,然后将其注入您的控制器类,例如
<bean id="test" class="com.spring.test.Test">
   <property name="process">
      <bean class="com.spring.test.Process"/>
   </property>
</bean>
public class Test {
   private Process process;

   public void setProcess(Process process) {
      this.process = process;
   }

   ...

   public String triggerNew() {  
      process.blah();
   }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读