Skip to content

Instantly share code, notes, and snippets.

@antic183
Last active August 18, 2021 01:08
Show Gist options
  • Save antic183/9d12124c4b8d25b00f2f111027023839 to your computer and use it in GitHub Desktop.
Save antic183/9d12124c4b8d25b00f2f111027023839 to your computer and use it in GitHub Desktop.
a simple google guice example
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import javax.inject.Singleton;
public class MainApp {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new AppInjector());
MyController app = injector.getInstance(MyController.class); // at this moment the data was injected
System.out.println(app.getDatabaseData());
}
}
class MyController {
@Inject //inject directly the property
private Database db;
// @Inject //injcting by param with setter methode. Or you can inject the data by contructor injection
// public void readDatabaseData(Database db) {
// this.db = db;
// }
public String getDatabaseData() {
return db.getData();
}
}
// configure which database should be used!
class AppInjector extends AbstractModule {
@Override
protected void configure() {
bind(Database.class).to(InMemoryDatabase.class);
}
}
interface Database {
public String getData();
}
@Singleton
class InMemoryDatabase implements Database {
@Override
public String getData() {
return "data from InMemoryDatabase";
}
}
@Singleton
class MySqlDatabase implements Database {
@Override
public String getData() {
return "data from MySqlDatabase";
}
}
@antic183
Copy link
Author

antic183 commented Feb 7, 2017

My pleasure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment