HarmonyOS 是否支持依赖注入,有没有可用的依赖注入框架?

如题:HarmonyOS 是否支持依赖注入,有没有可用的依赖注入框架?

阅读 536
1 个回答

利用reflect-metadata实现反射和注解机的功能:

import "reflect-metadata";
type PropertyKey = string;
// 定义 MyPropertyDecorator 装饰器函数,使用 Reflect.defineMetadata 进行属性注解
function MyPropertyDecorator(target: Object, propertyKey: PropertyKey): void {
  const metadataKey = `myProperty_${String(propertyKey)}`;
  Reflect.defineMetadata(metadataKey, "This is a custom annotation", target, propertyKey);
}
// 定义一个类,并在其中使用装饰器进行注解
class MyClass {
  @MyPropertyDecorator
  myProperty: string = "Hello, World!";
}
// 获取注解信息并输出
const metadataKey = `myProperty_myProperty`;
const annotation = Reflect.getMetadata(metadataKey, new MyClass(), "myProperty" as PropertyKey) as string;
console.log(annotation); // 输出:This is a custom annotation