Guice call init method after instantinating an object

前端 未结 8 1198
半阙折子戏
半阙折子戏 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 06:52

    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:

    
    class A {
        public A(Dependency1 d1, Dependency2 d2) {...}
    
        public postConstruct(RuntimeDependency dr) {...}
    }
    
    interface AFactory {
        A getInstance(RuntimeDependency dr);
    }
    
    class AFactoryImpl implements AFactory {
        @Inject
        public AFactoryImpl(Dependency1 d1, Dependency2 d2) {...}
    
        A getInstance(RuntimeDependency dr) {
            A a = new A(d1, d2);
            a. postConstruct(dr);
            return a;
        }
    }
    
    // in guice module
    bind(AFactory.class).to(AFactoryImpl.class)
    

提交回复
热议问题