Last active
August 18, 2021 01:08
-
-
Save antic183/9d12124c4b8d25b00f2f111027023839 to your computer and use it in GitHub Desktop.
a simple google guice example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My pleasure