前端JavaScript通过fetch或axios发起异步请求,调用Spring Boot后端接口;Spring使用@EnableAsync启用异步支持,@Async注解实现异步方法,配合DeferredResult非阻塞返回结果,提升系统响应能力。

JavaScript 本身是前端语言,而 Spring 是基于 Java 的后端框架,因此“JS 在 Spring 中实现异步调用”这个说法需要澄清:通常是指前端 JavaScript 发起异步请求(如 AJAX),调用 Spring 后端提供的异步接口。下面将从前后端配合的角度,完整说明如何实现这一过程。
前端通过 JavaScript(或现代框架如 Vue、React)发送异步 HTTP 请求到 Spring 服务。常用方式包括原生 fetch 或 axios 库。
示例:使用 fetch 发起 GET 请求
fetch('/api/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
axios.post('/api/data', { name: 'test' })
.then(response => {
console.log('Success:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
这些请求默认就是异步的,不会阻塞页面渲染。
为了让 Spring 接口支持真正的异步执行(即不占用主线程),需使用 Spring 的 @Async 注解。
1. 启用异步支持在主启动类上添加 @EnableAsync:
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
定义一个服务类,使用 @Async 标记方法:
@Service
public class AsyncService {
@Async
public CompletableFuture<String> doSomething() {
try {
Thread.sleep(3000); // 模拟耗时操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return CompletableFuture.completedFuture("Task Done");
}
}
Controller 接收请求并调用异步服务:
@RestController
@RequestMapping("/api")
public class DataController {
@Autowired
private AsyncService asyncService;
@GetMapping("/data")
public DeferredResult<String> getData() {
DeferredResult<String> result = new DeferredResult<>();
asyncService.doSomething().whenComplete((data, ex) -> {
if (ex != null) {
result.setErrorResult(ex);
} else {
result.setResult(data);
}
});
return result;
}
}
这里使用 DeferredResult 可以让 Controller 异步返回结果,避免阻塞请求线程。
前端 JS 与 Spring 后端常处于不同端口,需配置跨域访问权限。
在 Controller 上添加 @CrossOrigin
@CrossOrigin(origins = "http://localhost:3000") // 允许前端域名
@RestController
public class DataController { ... }
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
};
}
}
假设前端运行在 http://localhost:3000,后端在 http://localhost:8080。
基本上就这些。整个链路实现了 JS 发起异步调用,Spring 完成异步处理,提升系统响应能力。关键点在于前后端分离架构下,正确使用异步注解和非阻塞返回机制。
以上就是JS怎样在Spring中实现异步调用_JS在Spring中实现异步调用的完整教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号