Inject custom logic in Guice binding process

463 Views Asked by At

Is there a way to implement kind of before and after hook in Guice binding? E.g. before Guice calling a constructor to get the instance to be injected into a method, can I provide a logic check if the instance is already existed somewhere, if I can find the instance then I return it directly without calling the constructor; On the flip side is once an instance is constructed in Guice binding process, can I inject the logic to process that instance before it returned to the original caller?

1

There are 1 best solutions below

2
On BEST ANSWER

Using a custom Typelistener should do the trick. From what I understand your problem is similar to the "postConstruct" problem, executing code of an instance while guice is creating it. Maybe this (german) blog article wrote a while ago pushes you in the right direction.

  1. Using a Matcher to define on which instances the listener should react.
  2. using the afterInjection hook to work with the instance

    @Override public void configure(final Binder binder) { binder.bindListener(Matchers.any(), this); }

    @Override public void hear(final TypeLiteral type, final TypeEncounter encounter) { encounter.register(new InjectionListener() {

        @Override
        public void afterInjection(final I injectee) {
            // alle postconstruct Methoden (nie null) ausführen.
            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);
                }
            }
        }
    });
    

    }