[英]Understanding javax.inject example code?
I would very much appreciate someone helping me understand this javax example code and why the @inject annotation is actually useful/what it does.我非常感谢有人帮助我理解这个 javax 示例代码以及为什么 @inject 注释实际上很有用/它做了什么。 The code below comes from: Code From this Source下面的代码来自: Code From this Source
class Stopwatch {
final TimeSource timeSource;
@Inject Stopwatch(TimeSource TimeSource) {
this.TimeSource = TimeSource;
}
void start() { ... }
long stop() { ... }
}
First off, I think (I hope) there is a typo and the "TimeSource" parameter should really be "timeSource", since the field in the Stopwatch class is CamelCase.首先,我认为(我希望)有一个错字,“TimeSource”参数应该真的是“timeSource”,因为 Stopwatch 类中的字段是 CamelCase。
What I really don't understand though is what the @inject annotation is actually doing!?我真正不明白的是@inject 注释实际上在做什么!? Is it equivalent to this constructor?:它等价于这个构造函数吗?:
class Stopwatch {
final TimeSource timeSource;
Stopwatch(TimeSource timeSource) {
this.timeSource = timeSource;
}
}
Above is how I would handle adding the dependency, so I hope I'm correct that's how the @inject keyword does it... Or am I way off??以上是我将如何处理添加依赖项,所以我希望我是正确的,@inject 关键字就是这样做的......或者我离题了?
If you have understood Spring's @Autowired
annotation then, the code above is no different.如果您已经了解 Spring 的@Autowired
注释,那么上面的代码没有什么不同。 @Autowired
is a Spring specific annotation and @Inject
comes from the Java Dependency Injection specification @Autowired
是 Spring 特定的注解,@ @Inject
来自 Java 依赖注入规范
class Stopwatch {
final TimeSource timeSource;
@Inject Stopwatch(TimeSource TimeSource) {
this.TimeSource = TimeSource;
}
void start() { ... }
long stop() { ... }
}
Here, @Inject
is indicating that when the instance of Stopwatch
is created, it should be instantiated via that constructor and pass in an instance that is assignable to TimeSource
这里,@ @Inject
表示当创建Stopwatch
的实例时,它应该通过该构造函数实例化并传入一个可分配给TimeSource
的实例
Instead of the programmer calling a constructor or factory, a tool called a dependency injector passes dependencies to objects不是程序员调用构造函数或工厂,而是称为依赖注入器的工具将依赖传递给对象
So, as stated here, the dependency injector will make sure to inject an instance of TimeSource
while creating an instance of Stopwatch
.因此,正如此处所述,依赖项注入器将确保在创建Stopwatch
实例时注入TimeSource
实例。
Late answer but may help someone else.迟到的答案,但可能会帮助别人。 The @Inject annotation does nothing on its own. @Inject 注释本身什么都不做。
You need a framework that will act on the annotation.您需要一个对注释起作用的框架。
eg Guice例如吉斯
Injector injector = Guice.createInjector();
YourObject yo = injector.getInstance(YourObject.class);
The annotation is in javax to provide a standard name, so in theory I could swap Guice for something else.注释在 javax 中以提供标准名称,因此理论上我可以将 Guice 换成其他东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.