Search code examples
javaguicecode-injection

Post creation initialization of guice singleton


Is there a way to have guice call a init() method after it has instantiated a singleton? Calling init() inside the constructor is not an option since init() could be overriden by a subclass.


Solution

  • You can use `@PostConstruct' in guice when you use the mycila/jsr250 extension. This will cause your init() method to be called right after instantiation.

    @PostConstruct
    void init() {
         // ...
    }
    

    If you do not can/want to add 3rd party libs for this, I wrote a simple postconstruct module for this as well a while ago:

    public enum PostConstructModule implements Module, TypeListener {
    
    INSTANCE;
    
    @Override
    public void configure(final Binder binder) {
        // all instantiations will run through this typeListener
        binder.bindListener(Matchers.any(), this);
    }
    
    /**
     * Call postconstruct method (if annotation exists).
     */
    @Override
    public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) {
        encounter.register(new InjectionListener<I>() {
    
            @Override
            public void afterInjection(final I injectee) {
                for (final Method postConstructMethod : filter(asList(injectee.getClass().getMethods()), MethodPredicate.VALID_POSTCONSTRUCT)) {
                    try {
                        postConstructMethod.invoke(injectee);
                    } catch (final Exception e) {
                        throw new RuntimeException(format("@PostConstruct %s", postConstructMethod), e);
                    }
                }
            }
        });
       }
      }