NestJS 中的依赖注入是如何工作的?

NestJS 使用依赖注入(DI)来管理组件之间的依赖关系。通过在类的构造函数中使用 @Injectable() 装饰器,可以将服务注入到控制器或其他服务中。例如:

typescript复制代码

typescript 复制代码
import { Injectable } from '@nestjs/common';

@Injectable()
export class MyService {
  getData() {
    return 'Hello, World!';
  }
}

在控制器中注入服务:

typescript复制代码

typescript 复制代码
import { Controller, Get } from '@nestjs/common';
import { MyService } from './my.service';

@Controller()
export class MyController {
  constructor(private readonly myService: MyService) {}

  @Get()
  getData() {
    return this.myService.getData();
  }
}

NestJS 的 DI 容器会在运行时自动实例化服务,并将其注入到需要的地方。

相关推荐
SoaringHeart11 小时前
Flutter封装:原生路由管理极简封装 AppNavigator
前端·flutter
menu11 小时前
AI给我的建议
前端
张可爱11 小时前
20251018-JavaScript八股文整理版(上篇)
前端
小小测试开发11 小时前
Python Arrow库:告别datetime繁琐,优雅处理时间与时区
开发语言·前端·python
自律版Zz11 小时前
手写 Promise.resolve:从使用场景到实现的完整推导
前端·javascript
golang学习记11 小时前
从0死磕全栈之Next.js 自定义 Server 指南:何时使用及如何实现
前端
张可爱11 小时前
从奶茶店悟透 JavaScript:递归、继承、浮点数精度、尾递归全解析(通俗易懂版)
前端
梵得儿SHI11 小时前
Vue 开发环境搭建全指南:从工具准备到项目启动
前端·javascript·vue.js·node.js·pnpm·vue开发环境·nvm版本管理
八月ouc12 小时前
每日小知识点:10.14 webpack 有几种文件指纹
前端·webpack