Spring Boot如何异步运行方法呢?
下文笔者讲述SpringBoot异步运行的方法及示例分享,如下所示
异步运行方法的实现思路
在Springboot中,让方法异步,可采用以下方法 只需使用@EnableAsync 和 @Async两个注解 即可让方法异步运行 @EnableAsync: 加载Springboot启动类上 @Async: 加载异步的方法上例:异步方法的示例
package com.java265.aysncdemo.service; public interface AsyncService { void asyncMethod(String arg); } package com.java265.aysncdemo.service.ipml; import com.java265.aysncdemo.service.AsyncService; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncServiceImpl implements AsyncService { @Async @Override public void asyncMethod(String arg) { System.out.println("arg:" + arg); System.out.println("=====" + Thread.currentThread().getName() + "========="); } } @EnableAsync //在启动类或者配置类加上 @EnableAsync 注解 package com.java265.aysncdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @EnableAsync @SpringBootApplication public class AysncDemoApplication { public static void main(String[] args) { SpringApplication.run(AysncDemoApplication.class, args); } } //测试代码 package com.java265.aysncdemo; import com.java265.aysncdemo.service.AsyncService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class AysncDemoApplicationTests { @Autowired AsyncService asyncService; @Test public void testAsync() { System.out.println("=====" + Thread.currentThread().getName() + "========="); asyncService.asyncMethod("Async"); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。