On Github zabil / guiceprez
javax.inject (JSR 330)
public class Greeter{ Greeter(Output out){ ... } }
One way of construction
public class GreeterTest{ @Test public void shouldPrintAGreeting(){ Greeter greeter = new Greeter(mock(Output.class)); ... } }
public class Greeter{ @Inject Greeter(Output out){ ... } }
public interface Output{ void print(String message); }
public class Greeter{ @Inject Greeter(Output out){ out.print("Hello"); } }
public class ConsoleOutput implements Output { @Override void print(String message){ System.out.println(message); } }
public class ConsoleModule extends AbstractModule { @Override protected void configure(){ bind(Output.class).to(ConsoleOutput.class); } }
public static void main() { Injector injector = Guice.createInjector(new ConsoleModule()); Greeter greeter = injector.getInstance(Greeter.class); }
public class FileOutput extends Output { @Override void print(String message){ write(message); } }
public class ConsoleModule extends AbstractModule { @Override protected void configure(){ bind(Output.class).to(ConsoleOutput.class); } }
public class FileModule extends AbstractModule { @Override protected void configure(){ bind(Output.class).to(FileOutput.class); } }
public static void main() { injectorForConsole = Guice.createInjector(new ConsoleModule()); injectorForFile = Guice.createInjector(new FileModule()); consoleGreeter = injectorForConsole.getInstance(Greeter.class); fileGreeter = injectorForFile.getInstance(Greeter.class); }
public class DatabaseOutput extends Output { DatabaseOutput(DataSource source){ this.dataSource = dataSource; } @Override void print(String message){ // do something with dataSource } }
public class DatabaseModule extends AbstractModule { @Override protected void configure(){ bind(Output.class).to(DatabaseOutput.class); } @Provides DataSource provideDataSource() { WhateverDataSource dataSource = new WhateverDataSource(); dataSource.setJdbcUrl("my/database"); } }
public static void main() { injector = Guice.createInjector(new DatabaseModule()); greeter = injector.getInstance(Greeter.class); }