Guice 实例化对象后调用 init 方法
是否可以告诉 Guice 在之后调用某个方法(即 init()) 实例化给定类型的对象?
我在 EJB 3(和 Spring)中寻找类似于 @PostConstruct 注释的功能。
Is it possible to tell Guice to call some method (i.e. init()) after
instantinating an object of given type?
I look for functionality similar to @PostConstruct annotation in EJB 3 (and Spring).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您只需将
@Inject
注释添加到init()
方法中即可。实例化对象后它将自动运行。You can just add the
@Inject
annotation to yourinit()
method. It will get run automatically after the object is instantiated.事实上,这是可能的。
您需要定义一个
TypeListener
才能运行该功能。模块定义中的内容大致如下:Actually, it is possible.
You need to define a
TypeListener
to get the functionality going. Something along the lines of the following in your module definition:guiceyfruit 执行您对使用
@PostConstruct
注释的方法的操作或实现 spring 的InitializingBean
。也可以编写自己的侦听器来执行此操作。下面是一个在创建对象后调用公共init()
方法的示例。guiceyfruit does what you're after for methods annotated with
@PostConstruct
or implementing spring'sInitializingBean
. It's also possible to write your own listeners to do this. Here's an example that calls a publicinit()
method after objects are created.我喜欢 http://code.google.com/p/mycila/wiki/MycilaGuice。它支持 Guice 3,而不是 http://code.google.com/p/guiceyfruit。
I like http://code.google.com/p/mycila/wiki/MycilaGuice. This supports Guice 3, other than http://code.google.com/p/guiceyfruit.
如果您想在实例构造之后调用方法,则意味着构造后方法调用实际上是实例创建的一个步骤。在这种情况下,我会推荐抽象工厂设计模式来解决这个问题。
代码可能看起来像这样:
If you'd like to call a method after the construction of an instance, it means the post-construct method call is actually a step of the instance creation. In this case, I would recommend abstract factory design pattern to solve this problem.
The code may look like something like this:
GWizard 包含一个模块 (
gwizard-services
),它以 Guice 友好的格式提供 Guava 服务。 Guava 服务为您提供并行线程中的生命周期管理。https://github.com/stickfigure/gwizard
GWizard includes a module (
gwizard-services
) which provides Guava services in a Guice-friendly format. Guava services give you lifecycle management in parallel threads.https://github.com/stickfigure/gwizard
如果您需要使用其他对象初始化一个对象,并且在两个对象都准备好之后(如果您需要向另一个对象注册一个对象并且它们也相互依赖,就是这种情况),您可以轻松地这样做:
In case you need to initialize an object using other objects and after both are ready (which is the case if you need to register one with the other and they also depend on each other) you can easily do it like this:
根据 Geoff 的回答,您可以“使可调用”
@PostConstruct
方法:此外,您还可以多个
@PostConstruct
方法,但您将不知道它们将按什么顺序调用:Based on Geoff's answer you can "make callable"
@PostConstruct
method:Also, you can have multiple
@PostConstruct
method but you will not know in which order they are going to be invoked: