How do you stop Geek from introducing a class that is not bound in a module?

import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; public class GuiceDemo { public static void main(String[] args) { new GuiceDemo().run(); } public void run() { Injector injector = Guice.createInjector(new EmptyModule()); DemoInstance demoInstance = injector.getInstance(DemoInstance.class); assert(demoInstance.demoUnbound == null); } public static class EmptyModule extends AbstractModule { @Override protected void configure() { } } public static class DemoInstance { public final DemoUnbound demoUnbound; @Inject public DemoInstance(DemoUnbound demoUnbound) { this.demoUnbound = demoUnbound; } } public static class DemoUnbound { } } 

Is it possible to prevent Guice from providing an instance of DemoUnbound for the DemoInstance constructor?

In essence, I'm looking for a way to run Guice in a fully explicit binding mode, where injecting an unbound class is a mistake.

How do you make this a mistake for Guice to introduce a class not bound in a module?

+4
source share
2 answers

If you use the interface here instead of the specific class for DemoUnbound, Guice throws an exception because it cannot find a suitable class for input:

 public class GuiceDemo { public static void main(String[] args) { new GuiceDemo().run(); } public void run() { Injector injector = Guice.createInjector(new EmptyModule()); DemoInstance demoInstance = injector.getInstance(DemoInstance.class); assert(demoInstance.demoUnbound == null); } public static class EmptyModule extends AbstractModule { @Override protected void configure() { } } public static class DemoInstance { public final DemoUnbound demoUnbound; @Inject public DemoInstance(DemoUnbound demoUnbound) { this.demoUnbound = demoUnbound; } } public interface DemoUnbound { } } 
+5
source

Try adding binder().requireExplicitBindings(); into your module. This will not stop you from entering specific classes, but for this you will need the bind(DemoUnbound.class); module bind(DemoUnbound.class); to make it more obvious.

Read more in the Binder docs .

+9
source

Source: https://habr.com/ru/post/1434727/


All Articles