- Google Guice 教程
- Guice - 主頁
- Guice - 概述
- Guice - 環境設定
- Guice - 第一個應用程式
- 繫結示例
- Guice - 連結繫結
- Guice - 繫結註釋
- Guice - @Named 繫結
- Guice - 常量繫結
- Guice - @Provides 註釋
- Guice - 供應商類
- Guice - 建構函式繫結
- Guice - 內建繫結
- Guice - 即時繫結
- 注入示例
- Guice - 建構函式注入
- Guice - 方法注入
- Guice - 欄位注入
- Guice - 可選注入
- Guice - 按需注入
- 其它示例
- Guice - 作用域
- Guice - AOP
- Guice 實用資源
- Guice - 快速指南
- Guice - 實用資源
- Guice - 討論
Google Guice - 方法注入
注入是一個向物件注入依賴項的過程。方法注入用於將值物件作為依賴項設定到該物件。請參見下面的示例。
示例
建立一個名為 GuiceTester 的 Java 類。
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
public class GuiceTester {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new TextEditorModule());
TextEditor editor = injector.getInstance(TextEditor.class);
editor.makeSpellCheck();
}
}
class TextEditor {
private SpellChecker spellChecker;
@Inject
public TextEditor( SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void makeSpellCheck(){
spellChecker.checkSpelling();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(String.class)
.annotatedWith(Names.named("JDBC"))
.toInstance("jdbc:mysql://:5326/emp");
}
}
@ImplementedBy(SpellCheckerImpl.class)
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
private String dbUrl;
public SpellCheckerImpl(){}
@Inject
public void setDbUrl(@Named("JDBC") String dbUrl){
this.dbUrl = dbUrl;
}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
System.out.println(dbUrl);
}
}
輸出
編譯並執行檔案,您將看到以下輸出。
Inside checkSpelling. jdbc:mysql://:5326/emp
廣告