【发布时间】:2017-08-13 23:37:53
【问题描述】:
@Injectable 是什么意思
"允许将 whatever 注入到装饰器所在的类中"
或者
这是否意味着“允许我将这个类(上面的装饰器)注入到应用程序中的'wherever'”?
【问题讨论】:
标签: javascript angularjs spring frontend angular-fullstack
@Injectable 是什么意思
"允许将 whatever 注入到装饰器所在的类中"
或者
这是否意味着“允许我将这个类(上面的装饰器)注入到应用程序中的'wherever'”?
【问题讨论】:
标签: javascript angularjs spring frontend angular-fullstack
@Injectable 只是一个标记,告诉 Angular 引擎该类可以由 Injectors 创建。在运行时,Angular 告诉 Injectors 读取所有 @Injectable 类并实例化它们,并使它们可以被注入到引用它们的类中。
例如,假设有一个名为 UserService 的 Angular 服务,您需要在名为 RegistrationComponent 的组件中使用该服务。
@Injectable()
export class UserService {
saverUser(User user)
.....
}
然后在RegistrationComponent构造函数中声明一个引用UserService的输入参数,它告诉angular应该将UserService注入RegistrationComponent,当然之前@Injectable标记应该在UserService中声明
RegistrationComponent.ts
export class RegistrationComponent
constructor(private userService: UserService) { }
在 Spring 上下文中,@Component 与 @Injectable 发挥相似的作用,当然它们在实现上存在许多差异,但它们都扮演着相似的角色。 @Component 是一个注解,它告诉 Spring 某些特定的类必须被视为自动检测的候选对象,并且该类可以存在于 Spring 容器中。 Spring Container 中的组件(bean)可以注入到其他类中。
@Autowired 与 @Component 不同。 @Autowired 表示特定的类成员应该由 Spring DI 容器提供或注入。
更多信息请查看以下链接:
【讨论】: