Search code examples
javaexceptiondependency-injectionguiceillegalstateexception

What does it mean when I see "Re-entry is not allowed"?


I'm trying to do something like this.

class A extends B {
    Injector injector = Guice.CreateInjector(this);
    // ......statements...
}

It is throwing IllegalStateException : Re-entry is not allowed

com.google.inject.internal.util.$Preconditions.checkState(Preconditions.java:142)
    at com.google.inject.AbstractModule.configure(AbstractModule.java:55)
    at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:223)
    at com.google.inject.spi.Elements.getElements(Elements.java:101)
    at com.google.inject.internal.InjectorShell$Builder.build(InjectorShell.java:133)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:103)
    at com.google.inject.Guice.createInjector(Guice.java:95)
    at com.google.inject.Guice.createInjector(Guice.java:72)
    at com.google.inject.Guice.createInjector(Guice.java:62)

Why is this happening?


Solution

  • The only way this would happen is if you call Guice.createInjector() on the same module instance inside the configure method. It won't happen if you call it at object construction as you do in your example. Here's code that will reproduce that stack trace.

    class B extends AbstractModule {
        protected void configure() {
        }
    }
    
    public class A extends B {
      Injector injector;
    
      @Override
      protected void configure() {
        injector = Guice.createInjector(this);
      }
    }
    
    public class GuiceTest {
      public static void main(String... args) {
        A a = new A();
        Injector inj = Guice.createInjector(a);
      }
    }
    

    My response on how to fix it is... don't do this! There's never even remotely any reason to do this.

    Until you know what you're doing, you should never call Guice.createInjector() more than once in your application, and that once is usually in your Main class or in many cases in your static void main method itself.. I use Guice for everything and I still have never called it more than once in the same app. The idea is that you build your modules, pass them into your injector, and then let Guice inject everything else for you. See: Getting Started

    What are you trying to do that has made you try to do this? Note: Please don't answer me by editing your question or by commenting, as these two things will invalidate this answer. Instead, ask a new question that explains what you're really trying to do, and avoid the XY problem.