Guice call init method after instantinating an object

前端 未结 8 1186
半阙折子戏
半阙折子戏 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  void hear(final TypeLiteral typeLiteral, TypeEncounter typeEncounter) {
            typeEncounter.register(new InjectionListener() {
                @Override
                public void afterInjection(Object i) {
                    MyInitClass m = (MyInitClass) i;
                    m.init();
                }
            });
        }
    });
    

提交回复
热议问题