Guice,afterPropertiesSet

Rom*_*man 2 java guice

有人知道如何在Guice中实现与Spring中的' afterPropertiesSet '界面相同的功能?(它是一个建筑后挂钩)

And*_*mee 8

到目前为止,最简单的解决方案是,如果你正在使用构造函数注入而不做任何过于疯狂的事情,那就是创建一个构造后的方法并使用以下方法对其进行注释@Inject:

final class FooImpl implements Foo {
  private final Bar bar;

  @Inject
  FooImpl(Bar bar) {
    this.bar = bar;

    ...
  }

  @Inject
  void init() {
    // Post-construction code goes here!
  }
}
Run Code Online (Sandbox Code Playgroud)

当Guice提供FooImpl时,它会看到它有一个@Inject构造函数,调用它,然后搜索带注释的方法@Inject并调用它们.预期的用例是setter注入,但即使@Inject方法没有params,Guice也会调用它.

如果你使用setter或field injection来注入deps,我不推荐使用它,因为我不知道Guice @Inject是否对调用方法的顺序做出任何保证(也就是说,你的init()方法可能无法保证叫做最后).也就是说,无论如何,构造函数注入是首选方法,因此这应该是一个非问题.


Tim*_*per 5

我想使用@PostConstruct是要走的路.

这是一篇相关的博文:http://macstrac.blogspot.com/2008/10/adding-support-for-postconstruct.html

这是一个提供支持的插件库:http://code.google.com/p/guiceyfruit/

此处描述了通过Guiceyfruit添加生命周期支持:http://code.google.com/p/guiceyfruit/wiki/Lifecycle