第一章 NestJS与SpringBoot框架对比
一.框架简介
1.Spring 和 Spring Boot
Spring 作者 Rod Johnson 出生于澳大利亚,现居伦敦, 毕业于悉尼大学计算机系, 音乐学的博士。著作《Expert One-on-One J2EE》,这本书写于2002年末。
Spring项目是从2003年2月份启动, 其中的基础代码来自Johnson《Expert One-on-One J2EE 》。
在2004年由Rod Johnson主导的Spring项目推出了1.0版本,这彻底地改变了Java EE开发的世界,很快人们就抛弃了繁重的EJB的标准,迅速地投入到了Spring框架中,于是Spring成为了现实中Java EE开发的标准。
Spring以强大的控制反转(IoC)来管理各类Java资源,从而降低了各种资源的耦合;并且提供了极低的侵入性,也就是使用Spring框架开发的编码,脱离了Spring API也可以继续使用。
而Spring的面向切面的编程(AOP)通过动态代理技术,允许我们按照约定进行配置编程,进而增强了Bean的功能,它擦除了大量重复的代码,如数据库编程所需大量的try…catch…finally…语句以及数据库事务控制代码逻辑,使得开发人员能够更加集中精力于业务开发,而非资源功能性的开发。
Spring还提供许多整合了当时非常流行的框架的模板,如持久层Hibernate的HibernateTemplate模板、iBATIS的SqlMapClientTemplate模板等,极大地融合并简化了当时主流技术的使用,使得其展示了强有力的生命力。
经过多年迭代后Spring变得越来越庞大,配置变得越来越繁琐, 这偏离了Spring的设计初衷,所以在2013年,Pivotal团队就开始研发SpringBoot。
2014年4月,发布全新开源的轻量级框架的第一个SpringBoot版本。
Spring Boot 是 Spring Framework 的引导程序, 主要设计目的是用来简化Spring应用的初始搭建和开发过程。致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
Spring Framework 是 Spring Boot 的基础。
附带介绍下Pivotal 公司, Pivotal 公司,可谓是大牛云集,公司的开源产品有:Spring 以及 Spring 衍生产品、Web 服务器 Tomcat、缓存中间件 Redis、消息中间件 RabbitMQ、平台即服务的 Cloud Foundry、Greenplum 数据引擎、还有大名鼎鼎的 GemFire。
这些著名开源产品背后的开发者都在 Pivotal 公司,其研发团队汇集了全球的一流开发者。
优势:
1.大量成熟组件;
2.支持多线程;
3.更容易维护。
劣势:
1.高内存使用率;
2.没用的依赖比较多;
3.大量的模板代码导致调式变困难。
2.Nestjs
作者 Kamil Myśliwiec, 一个热情的软件工程师,喜欢挑战、最新的技术和编程。 为大公司做过项目,比如Orsay(与名人Anna Wendzikowska合作)、Wedel(波兰最古老的巧克力品牌)和惠普企业。 是nestjs的创造者、TrilonIO创始人之一、 google开发专家。 同时也是一名演讲者、培训师和顾问。
NestJS框架是2016年底开始开发的。
以下摘自 Angular.love 对作者本人的采访.
Maciej Sikorski: What motivated you to create NestJS? Haven’t people advised you against writing your own framework?
Kamil Myśliwiec: When I started working on Nest in late 2016, I didn’t set myself any specific goals. I never even assumed that the project would eventually gain such popularity and turn into a full-fledged framework. You could say that at the beginning, it was just a side-project that I worked on late at night. I didn’t have any expectations though, I just continued to work on implementing new functionalities that I would like the framework I use to offer in the way that I thought was “the best”. Every Twitter mention or a Github star was very rewarding, a reason for joy and motivation for further work.
设计哲学
近几年,由于 Node.js,JavaScript 已经成为 Web 前端和后端应用程序的「通用语言」,从而产生了像Angular、React、Vue等令人耳目一新的项目,这些项目提高了开发人员的生产力,使得可以快速构建可测试的且可扩展的前端应用程序。 然而,在服务器端,虽然有很多优秀的库、helper 和 Node 工具,但是它们都没有有效地解决主要问题 - 架构。
Nest 旨在提供一个开箱即用的应用程序体系结构,允许轻松创建高度可测试,可扩展,松散耦合且易于维护的应用程序。
优势:
1.轻量级,更快;
2.更擅长处理 I/O任务;
3.单线程,内存使用率低。
劣势:
1.缺少多线程支持;
2.执行计算量大的任务时表现不佳;
3.缺少严格的类型检测,更容易出现导致运行时问题。(如果使用TypeScript 也会避免此问题)
二.示例对比
1.引导程序
Spring boot
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Nest-TypeScript版本
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(80);
}
bootstrap();
2.Controller
Spring boot
@RestController
public class AppController {
@Autowired
@Qualifier(value = "appV2")
private AppService appService;
@GetMapping("/")
String getHello(){
return this.appService.getHello();
}
@GetMapping("/find/{id}")
String findOne(@PathVariable String id){
return String.format("This action returns a #%s cat", id);
}
@GetMapping("/login")
String login(@RequestParam(required = false) String name, @RequestParam(required = false) String pwd){
return String.format("name: %s, pwd:%s", name, pwd);
}
}
NestJS
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get('/find/:id')
findOne(@Param('id') id: string){
return `This action returns a #${id} cat`;
}
@Get('/login')
login(@Query('name') name: string, @Query('pwd') pwd: string){
return `name: ${name}, pwd:${pwd}`;
}
}
3.Service
Spring boot
@Service
public interface AppService {
String getHello();
}
@Component("appV1")
public class AppServiceImplV1 implements AppService{
@Override
public String getHello() {
return "Hello World!";
}
}
@Component("appV2")
public class AppServiceImplV2 implements AppService{
@Override
public String getHello() {
return "Hello World V2";
}
}
NestJS
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
三.总结
1.从示例可看出SpringBoot和NestJS的TypeScript版本很相似,所以很多人称NestJS是Node版的Spring;
2.开发同样的功能,二者的代码量相当;
3.选择使用哪个框架主要看业务需求,如果业务是I/O任务为主, 建议使用NestJS, 而且目前TypeScript是写后端的最佳选择。