Guice , afterPropertiesSet

前端 未结 4 518
不思量自难忘°
不思量自难忘° 2021-01-07 05:19

Someone knows some way that how can I achieve the same functionality in Guice as the \'afterPropertiesSet\' interface in spring ? ( its a post construction hook )

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-07 05:47

    By far the simplest solution, if you're using constructor injection and not doing anything too crazy, is to create a post-construction method and annotate it with @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!
      }
    }
    

    When Guice provides FooImpl, it'll see it has an @Inject constructor, call it, and then search for methods annotated with @Inject and call those. The intended use case for this is setter injection, but even if an @Inject method has no params, Guice will call it.

    I don't recommend using this if you're using setter or field injection to inject deps since I don't know if Guice makes any guarantees about the order in which @Inject methods are called (that is, your init() method might not be guaranteed to be called last). That said, constructor injection is the preferred approach anyway, so that should be a non-issue.

提交回复
热议问题