SpringBoot测试类
POM添加依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> </parent>
<!--测试包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency>
测试类编写
@RunWith(SpringRunner.class) @SpringBootTest(classes = {SpringAsyncConfig.class}) public class SpringbootTest { @Autowired private SpringAsyncConfig SpringAsyncConfig; @Test public void NacosTest() { SpringAsyncConfig.asyncMethodWithReturnType(); } }
依赖类
@Configuration @EnableAsync public class SpringAsyncConfig { @Bean("mytaskExecutor") public TaskExecutor taskExecutor(){ ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setThreadNamePrefix("taskExecutor"); threadPoolTaskExecutor.setCorePoolSize(10); threadPoolTaskExecutor.setMaxPoolSize(30); threadPoolTaskExecutor.setQueueCapacity(100); threadPoolTaskExecutor.afterPropertiesSet(); return threadPoolTaskExecutor; } @Async //标注使用 public void asyncMethodWithVoidReturnType() { System.out.println("Execute method asynchronously. " + Thread.currentThread().getName()); } @Async public Future<String> asyncMethodWithReturnType() { System.out.println("Execute method asynchronously - " + Thread.currentThread().getName()); try { Thread.sleep(5000); return new AsyncResult<String>("hello world !!!!"); } catch (InterruptedException e) { // } return null; } @Test public void run(){ } public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringAsyncConfig.class); SpringAsyncConfig bean = (SpringAsyncConfig) context.getBean("springAsyncConfig"); bean.asyncMethodWithReturnType(); Future<String> str = bean.asyncMethodWithReturnType(); System.out.println(str); System.out.println("121"); } }
借鉴 https://blog.csdn.net/lixinkuan328/article/details/121396675