Guice call init method after instantinating an object

前端 未结 8 1070
半阙折子戏
半阙折子戏 2020-11-28 06:21

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 annot

相关标签:
8条回答
  • 2020-11-28 07:14

    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:

    bindListener(Matchers.subclassesOf(MyInitClass.class), new TypeListener() {
        @Override
        public <I> void hear(final TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
            typeEncounter.register(new InjectionListener<I>() {
                @Override
                public void afterInjection(Object i) {
                    MyInitClass m = (MyInitClass) i;
                    m.init();
                }
            });
        }
    });
    
    0 讨论(0)
  • 2020-11-28 07:14

    I like http://code.google.com/p/mycila/wiki/MycilaGuice. This supports Guice 3, other than http://code.google.com/p/guiceyfruit.

    0 讨论(0)
提交回复
热议问题