springboot启动后异步启动一个程序

@Async
@EnableAsync
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication
@EnableAsync
public class MyApplication { public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
  1. 创建一个服务类: 创建一个服务类,包含你要异步执行的方法。
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; @Service
public class MyAsyncService { @Async
public void asyncMethod() {
// 在这里编写你的异步方法逻辑
System.out.println("异步方法被执行了");
}
}
mainMyAsyncService
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext; @SpringBootApplication
@EnableAsync
public class MyApplication { public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(MyApplication.class, args);
MyAsyncService myAsyncService = context.getBean(MyAsyncService.class);
myAsyncService.asyncMethod();
}
}
main
@Async