Guice-quick-guide
Google Guice-概要
Guiceは、オープンソースのJavaベースの依存性注入フレームワークです。 これは軽量であり、Googleによって開発および管理されています。 この章では、Guiceフレームワークの概要を説明します。
依存性注入
すべてのJavaベースのアプリケーションには、連携して動作し、エンドユーザーが動作しているアプリケーションと見なすものを提示するオブジェクトがいくつかあります。 複雑なJavaアプリケーションを記述する場合、アプリケーションクラスは他のJavaクラスから可能な限り独立している必要があります。これにより、これらのクラスを再利用し、ユニットテスト中に他のクラスとは独立してテストできるようになります。 依存性注入(またはワイヤリングと呼ばれることもあります)は、これらのクラスを接着し、同時にそれらを独立した状態に保つのに役立ちます。
テキストエディタコンポーネントを備えたアプリケーションがあり、スペルチェックを提供したいと考えています。 標準コードは次のようになります-
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor() {
spellChecker = new SpellChecker();
}
}
ここで、TextEditorとSpellCheckerの間に依存関係が作成されていることに注意してください。 制御の反転シナリオでは、代わりにこのようなことをします-
public class TextEditor {
private SpellChecker spellChecker;
@Inject
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
}
ここでは、TextEditorはSpellCheckerの実装について心配するべきではありません。 SpellCheckerは独立して実装され、TextEditorのインスタンス化時にTextEditorに提供されます。
Guiceを使用した依存性注入(バインディング)
依存性注入は、Guice Bindingsによって制御されます。 Guiceはバインディングを使用して、オブジェクトタイプを実際の実装にマップします。 これらのバインディングはモジュールとして定義されます。 モジュールは、以下に示すようにバインディングのコレクションです-
public class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
/*
*Bind SpellChecker binding to WinWordSpellChecker implementation
* whenever spellChecker dependency is used.
*/
bind(SpellChecker.class).to(WinWordSpellChecker.class);
}
}
インジェクタはオブジェクトグラフビルダであり、モジュールはそのコアビルディングブロックです。 したがって、最初のステップは、インジェクターを作成し、インジェクターを使用してオブジェクトを取得することです。
public static void main(String[] args) {
/*
*Guice.createInjector() takes Modules, and returns a new Injector
* instance. This method is to be called once during application startup.
*/
Injector injector = Guice.createInjector(new TextEditorModule());
/*
*Build object using injector
*/
TextEditor textEditor = injector.getInstance(TextEditor.class);
}
上記の例では、TextEditorクラスオブジェクトグラフはGuiceによって構築され、このグラフにはTextEditorオブジェクトとその依存関係がWinWordSpellCheckerオブジェクトとして含まれています。
Google Guice-環境設定
Guiceの機能を検討する前に、Guiceの環境設定について見ていきましょう。
ローカル環境のセットアップ
このセクションでは、マシンにJava環境をダウンロードしてセットアップする方法について説明します。 環境をセットアップするには、以下の手順に従ってください。
Java SEは、https://java.sun.com/javase/downloads/index_jdk5.jsp [Javaのダウンロード]リンクから無料で入手できます。 オペレーティングシステムに基づいてバージョンをダウンロードします。 次に、指示に従ってJavaをダウンロードし、.exeファイルを実行してJavaをマシンにインストールします。 Javaをインストールしたら、正しいインストールディレクトリを指すように環境変数を設定する必要があります。
Windows 2000/XPのパスのセットアップ
_c:\ Program Files \ java \ jdk_ディレクトリにJavaがインストールされていると想定しています-
- 「マイコンピュータ」を右クリックして、「プロパティ」を選択します。
- 「詳細」タブの下の「環境変数」ボタンをクリックします。
- ここで、「Path」変数を変更して、Java実行可能ファイルへのパスも含まれるようにします。 たとえば、パスが現在 'C:\ WINDOWS \ SYSTEM32' に設定されている場合、パスを 'C:\ WINDOWS \ SYSTEM32; c:\ Program Files \ java \ jdk \ bin' に変更します。
Windows 95/98/MEのパスのセットアップ
場合は、Javaを c:\ Program Files \ java \ jdkdirectory にインストールし、 'C:\ autoexec.bat' ファイルを編集して、最後に次の行を追加します:* 'SET PATH =%PATH% ; C:\ Program Files \ java \ jdk \ bin '*。
Linux、UNIX、Solaris、FreeBSDのパスのセットアップ
環境変数PATHは、Javaバイナリがインストールされている場所を指すように設定する必要があります。 詳細については、シェルのドキュメントを参照してください。
たとえば、シェルとして bash を使用する場合、次の行を最後に追加します。 '。bashrc:export PATH =/path/to/java:$ PATH'
人気のあるJavaエディター
Javaプログラムを作成するには、テキストエディターが必要です。 市場には多くの洗練されたIDEがあります。 しかし、今のところ、次のいずれかを検討することができます-
- メモ帳-Windowsマシンでは、メモ帳(このチュートリアルで推奨)、TextPadなどの単純なテキストエディタを使用できます。
- Netbeans -これは、オープンソースで無料のJava IDEであり、https://www.netbeans.org/indexlからダウンロードできます。
- Eclipse -また、eclipseオープンソースコミュニティによって開発されたJava IDEであり、https://www.eclipse.org/からダウンロードできます。
Google Guice環境
Google Guiceの最新バージョンと関連するjarファイルをダウンロードします。
このチュートリアルを書いている時点で、C:\> Googleフォルダーにコピーしました。
OS | Archive name |
---|---|
Windows | guice-4.1.0.jar;aopalliance-1.0.jar;guava-16.0.1.jar;javax.inject-1.jar |
Linux | guice-4.1.0.jar;aopalliance-1.0.jar;guava-16.0.1.jar;javax.inject-1.jar |
Mac | guice-4.1.0.jar;aopalliance-1.0.jar;guava-16.0.1.jar;javax.inject-1.jar |
CLASSPATH変数を設定する
Guice jarの場所を指すように CLASSPATH 環境変数を設定します。 次のように、さまざまなオペレーティングシステムのGoogleフォルダにGuiceと関連するjarを保存していると仮定します。
OS | Output |
---|---|
Windows | Set the environment variable CLASSPATH to %CLASSPATH%;C:\Google\guice-4.1.0.jar;C:\Google\aopalliance-1.0.jar;C:\Google\guava-16.0.1.jar;C:\Google\javax.inject-1.jar;.; |
Linux | export CLASSPATH=$CLASSPATH:Google/guice-4.1.0.jar:Google/aopalliance-1.0.jar:Google/guava-16.0.1.jar:Google/javax.inject-1.jar:. |
Mac | export CLASSPATH=$CLASSPATH:Google/guice-4.1.0.jar:Google/aopalliance-1.0.jar:Google/guava-16.0.1.jar:Google/javax.inject-1.jar:. |
Google Guice-最初のアプリケーション
Guiceバインディングメカニズムを使用して依存関係の注入を段階的に示すサンプルコンソールベースのアプリケーションを作成しましょう。
- ステップ1 *-インターフェースの作成
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
- ステップ2 *-実装の作成
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
- ステップ3 *-バインディングモジュールの作成
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).to(SpellCheckerImpl.class);
}
}
- ステップ4 *-依存関係を持つクラスを作成する
class TextEditor {
private SpellChecker spellChecker;
@Inject
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void makeSpellCheck() {
spellChecker.checkSpelling();
}
}
- ステップ5 *-インジェクターを作成する
Injector injector = Guice.createInjector(new TextEditorModule());
- ステップ6 *-依存関係が満たされたオブジェクトを取得する
TextEditor editor = injector.getInstance(TextEditor.class);
- ステップ7 *-オブジェクトを使用する
editor.makeSpellCheck();
完全な例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
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(SpellChecker.class).to(SpellCheckerImpl.class);
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
出力
ファイルをコンパイルして実行すると、次の出力が表示されます。
Inside checkSpelling.
Google Guice-リンクバインディング
リンクバインディングでは、Guiceは型をその実装にマップします。 以下で説明する例では、SpellCheckerインターフェースをその実装 SpellCheckerImpl にマッピングしています。
bind(SpellChecker.class).to(SpellCheckerImpl.class);
具象クラスをそのサブクラスにマッピングすることもできます。 以下の例を参照してください-
bind(SpellCheckerImpl.class).to(WinWordSpellCheckerImpl.class);
ここでバインディングを連鎖していることに注目してください。 完全な例で結果を見てみましょう。
完全な例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
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(SpellChecker.class).to(SpellCheckerImpl.class);
bind(SpellCheckerImpl.class).to(WinWordSpellCheckerImpl.class);
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
//subclass of SpellCheckerImpl
class WinWordSpellCheckerImpl extends SpellCheckerImpl {
@Override
public void checkSpelling() {
System.out.println("Inside WinWordSpellCheckerImpl.checkSpelling." );
}
}
出力
ファイルをコンパイルして実行すると、次の出力が表示されます。
Inside WinWordSpellCheckerImpl.checkSpelling.
Google Guice-注釈のバインド
型をその実装にバインドできるため。 複数の実装を持つ型をマップする場合、カスタムアノテーションも作成できます。 概念を理解するには、以下の例を参照してください。
バインディングアノテーションを作成する
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface WinWord {}
- @ BindingAnnotation -注釈をバインディング注釈としてマークします。
- @ Target -注釈の適用可能性を示します。
- @ Retention -アノテーションの可用性をランタイムとしてマークします。
バインディングアノテーションを使用したマッピング
bind(SpellChecker.class).annotatedWith(WinWord.class).to(WinWordSpellCheckerImpl.class);
バインディングアノテーションを使用して注入する
@Inject
public TextEditor(@WinWord SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
完全な例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import java.lang.annotation.Target;
import com.google.inject.AbstractModule;
import com.google.inject.BindingAnnotation;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface WinWord {}
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(@WinWord SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void makeSpellCheck() {
spellChecker.checkSpelling();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).annotatedWith(WinWord.class)
.to(WinWordSpellCheckerImpl.class);
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
//subclass of SpellCheckerImpl
class WinWordSpellCheckerImpl extends SpellCheckerImpl {
@Override
public void checkSpelling() {
System.out.println("Inside WinWordSpellCheckerImpl.checkSpelling." );
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
Inside WinWordSpellCheckerImpl.checkSpelling.
Google Guice-@Named Binding
Guiceは、カスタムアノテーションを作成せずにバインディングをマップする別の方法も提供します。 @Namedアノテーションを使用することができます。
名前付き注釈を使用したマッピング
bind(SpellChecker.class).annotatedWith(Names.named("OpenOffice")).to(OpenOfficeWordSpellCheckerImpl.class);
@Named注釈を使用して注入する
@Inject
public TextEditor(@Named("OpenOffice") SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
完全な例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
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(@Named("OpenOffice") SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void makeSpellCheck() {
spellChecker.checkSpelling();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).annotatedWith(Names.named("OpenOffice"))
.to(OpenOfficeWordSpellCheckerImpl.class);
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
//subclass of SpellCheckerImpl
class OpenOfficeWordSpellCheckerImpl extends SpellCheckerImpl {
@Override
public void checkSpelling() {
System.out.println("Inside OpenOfficeWordSpellCheckerImpl.checkSpelling." );
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
Inside OpenOfficeWordSpellCheckerImpl.checkSpelling.
Google Guice-定数バインディング
Guiceは、値オブジェクトまたは定数を使用してバインディングを作成する方法を提供します。 JDBC URLを設定する場合を考えてください。
@Named注釈を使用して注入する
@Inject
public void connectDatabase(@Named("JBDC") String dbUrl) {
//...
}
これは、* toInstance()*メソッドを使用して達成できます。
bind(String.class).annotatedWith(Names.named("JBDC")).toInstance("jdbc:mysql://localhost:5326/emp");
完全な例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
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.makeConnection();
}
}
class TextEditor {
private String dbUrl;
@Inject
public TextEditor(@Named("JDBC") String dbUrl) {
this.dbUrl = dbUrl;
}
public void makeConnection() {
System.out.println(dbUrl);
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(String.class)
.annotatedWith(Names.named("JDBC"))
.toInstance("jdbc:mysql://localhost:5326/emp");
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
jdbc:mysql://localhost:5326/emp
Google Guice-@Providesアノテーション
Guiceは、 @ provides メソッドを使用して、複雑なオブジェクトとのバインディングを作成する方法を提供します。
@Provides
public SpellChecker provideSpellChecker() {
String dbUrl = "jdbc:mysql://localhost:5326/emp";
String user = "user";
int timeout = 100;
SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
return SpellChecker;
}
このメソッドはバインディングモジュールの一部であり、マッピングされる複雑なオブジェクトを提供します。 下記の完全な例を参照してください。
完全な例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provides;
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() {}
@Provides
public SpellChecker provideSpellChecker() {
String dbUrl = "jdbc:mysql://localhost:5326/emp";
String user = "user";
int timeout = 100;
SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
return SpellChecker;
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
private String dbUrl;
private String user;
private Integer timeout;
@Inject
public SpellCheckerImpl(String dbUrl,
String user,
Integer timeout) {
this.dbUrl = dbUrl;
this.user = user;
this.timeout = timeout;
}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
System.out.println(dbUrl);
System.out.println(user);
System.out.println(timeout);
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
Inside checkSpelling.
jdbc:mysql://localhost:5326/emp
user
100
Google Guice-プロバイダークラス
@providesメソッドがより複雑になると、Providerインターフェイスを使用してこのメソッドを別のクラスに移動できます。
class SpellCheckerProvider implements Provider<SpellChecker> {
@Override
public SpellChecker get() {
String dbUrl = "jdbc:mysql://localhost:5326/emp";
String user = "user";
int timeout = 100;
SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
return SpellChecker;
}
}
次に、プロバイダーをタイプにマップする必要があります。
bind(SpellChecker.class).toProvider(SpellCheckerProvider.class);
下記の完全な例を参照してください。
完全な例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
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(SpellChecker.class).toProvider(SpellCheckerProvider.class);
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
private String dbUrl;
private String user;
private Integer timeout;
@Inject
public SpellCheckerImpl(String dbUrl,
String user,
Integer timeout) {
this.dbUrl = dbUrl;
this.user = user;
this.timeout = timeout;
}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
System.out.println(dbUrl);
System.out.println(user);
System.out.println(timeout);
}
}
class SpellCheckerProvider implements Provider<SpellChecker> {
@Override
public SpellChecker get() {
String dbUrl = "jdbc:mysql://localhost:5326/emp";
String user = "user";
int timeout = 100;
SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
return SpellChecker;
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
Inside checkSpelling.
jdbc:mysql://localhost:5326/emp
user
100
Google Guice-コンストラクターバインディング
Guiceは、* toConstructor()*メソッドを使用して、オブジェクトの特定のコンストラクターでバインディングを作成する方法を提供します。
@Override
protected void configure() {
try {
bind(SpellChecker.class)
.toConstructor(SpellCheckerImpl.class.getConstructor(String.class));
} catch (NoSuchMethodException | SecurityException e) {
System.out.println("Required constructor missing");
}
}
下記の完全な例を参照してください。
完全な例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
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() {
try {
bind(SpellChecker.class)
.toConstructor(SpellCheckerImpl.class.getConstructor(String.class));
} catch (NoSuchMethodException | SecurityException e) {
System.out.println("Required constructor missing");
}
bind(String.class)
.annotatedWith(Names.named("JDBC"))
.toInstance("jdbc:mysql://localhost:5326/emp");
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
private String dbUrl;
public SpellCheckerImpl(){}
public SpellCheckerImpl(@Named("JDBC") String dbUrl) {
this.dbUrl = dbUrl;
}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
System.out.println(dbUrl);
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
Inside checkSpelling.
jdbc:mysql://localhost:5326/emp
Google Guice-組み込みのバインディング
Guiceは java.util.logging.Logger クラスの組み込みバインディングを提供します。 ロガーの名前は、ロガーが挿入されるクラスの名前に自動的に設定されます。 下記の例をご覧ください。
例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import java.util.logging.Logger;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
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 Logger logger;
@Inject
public TextEditor( Logger logger) {
this.logger = logger;
}
public void makeSpellCheck() {
logger.info("In TextEditor.makeSpellCheck() method");
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
Dec 20, 2017 12:51:05 PM TextEditor makeSpellCheck
INFO: In TextEditor.makeSpellCheck() method
Google Guice-ジャストインタイムバインディング
バインディングはBinding Moduleで定義されているため、Guiceは依存関係を注入する必要がある場合は常にバインディングを使用します。 バインディングが存在しない場合、ジャストインタイムバインディングの作成を試みることができます。 バインディングモジュールに存在するバインディングは*明示的バインディング*と呼ばれ、優先順位が高くなりますが、ジャストインタイムバインディングは*暗黙的バインディング*と呼ばれます。 両方のタイプのバインディングが存在する場合、明示的なバインディングがマッピングのために考慮されることに注意してください。
ジャストインタイムバインディングの3つのタイプの例を以下に示します-
Sr.No. | Binding Type & Description |
---|---|
1 |
非プライベート、引数なしのコンストラクターは、ジャストインタイムバインディングの対象となります。 別の方法は、コンストラクタに@Injectアノテーションを付けることです。 |
2 |
@ImplementatedByアノテーションは、実装クラスについて説明します。 このような場合、バインディングモジュールではバインディングは必要ありません。 |
3 |
@ProvidedByアノテーションは、実装クラスのプロバイダーについて説明します。 このような場合、バインディングモジュールではバインディングは必要ありません。 |
Google Guice-コンストラクターインジェクション
インジェクションは、オブジェクトに依存関係を注入するプロセスです。 コンストラクター注入は非常に一般的です。 このプロセスでは、コンストラクターへの引数として依存関係が注入されます。 下記の例をご覧ください。
例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
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(SpellChecker.class).to(SpellCheckerImpl.class);
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
Inside checkSpelling.
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://localhost: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://localhost:5326/emp
Google Guice-フィールドインジェクション
インジェクションは、オブジェクトに依存関係を注入するプロセスです。 フィールドインジェクションは、値オブジェクトをオブジェクトのフィールドへの依存関係として設定するために使用されます。 下記の例をご覧ください。
例
GuiceTesterという名前のJavaクラスを作成します。
*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://localhost:5326/emp");
}
}
@ImplementedBy(SpellCheckerImpl.class)
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Inject @Named("JDBC")
private String dbUrl;
public SpellCheckerImpl(){}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
System.out.println(dbUrl);
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
Inside checkSpelling.
jdbc:mysql://localhost:5326/emp
Google Guice-オプションのインジェクション
インジェクションは、オブジェクトに依存関係を注入するプロセスです。 オプションの注入とは、存在する場合に依存関係を注入することです。 メソッドとフィールドの注入はオプションで依存する場合があり、依存関係が存在しない場合はデフォルト値が必要です。 下記の例をご覧ください。
例
GuiceTesterという名前のJavaクラスを作成します。
*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;
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() {}
}
@ImplementedBy(SpellCheckerImpl.class)
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
private String dbUrl = "jdbc:mysql://localhost:5326/emp";
public SpellCheckerImpl(){}
@Inject(optional=true)
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://localhost:5326/emp
Google Guice-オンデマンドインジェクション
インジェクションは、オブジェクトに依存関係を注入するプロセスです。 メソッドとフィールドの注入は、* injector.injectMembers()*メソッドを使用して既存のオブジェクトを使用して初期化するために使用できます。 下記の例をご覧ください。
例
GuiceTesterという名前のJavaクラスを作成します。
*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;
public class GuiceTester {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new TextEditorModule());
SpellChecker spellChecker = new SpellCheckerImpl();
injector.injectMembers(spellChecker);
TextEditor editor = injector.getInstance(TextEditor.class);
editor.makeSpellCheck();
}
}
class TextEditor {
private SpellChecker spellChecker;
@Inject
public void setSpellChecker(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public TextEditor() { }
public void makeSpellCheck() {
spellChecker.checkSpelling();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
}
}
@ImplementedBy(SpellCheckerImpl.class)
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
public SpellCheckerImpl(){}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
出力
次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-
Inside checkSpelling.
Google Guice-スコープ
Guiceは、デフォルトの動作として値を提供するたびに新しいインスタンスを返します。 スコープを介して構成できます。 Guiceがサポートするさまざまなスコープは-
- @ Singleton -アプリケーションの存続期間の単一インスタンス。 @Singletonオブジェクトはスレッドセーフである必要があります。
- @ SessionScoped -Webアプリケーションの特定のセッションの単一インスタンス。 @SessionScopedオブジェクトはスレッドセーフである必要があります。
- @ RequestScoped -Webアプリケーションの特定のリクエストの単一インスタンス。 @RequestScopedオブジェクトはスレッドセーフである必要はありません。
スコープの適用
次の方法でスコープを適用できます-
クラスレベルで
@Singleton
class SpellCheckerImpl implements SpellChecker {
public SpellCheckerImpl(){}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
構成レベルで
bind(SpellChecker.class).to(SpellCheckerImpl.class).in(Singleton.class);
メソッドレベルで
@Provides @Singleton
public SpellChecker provideSpellChecker() {
String dbUrl = "jdbc:mysql://localhost:5326/emp";
String user = "user";
int timeout = 100;
SpellChecker SpellChecker = new SpellCheckerImpl(dbUrl, user, timeout);
return SpellChecker;
}
例
動作中のクラスレベルのスコープを見てみましょう。
@Singletonアノテーションの結果
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
public class GuiceTester {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new TextEditorModule());
SpellChecker spellChecker = new SpellCheckerImpl();
injector.injectMembers(spellChecker);
TextEditor editor = injector.getInstance(TextEditor.class);
System.out.println(editor.getSpellCheckerId());
TextEditor editor1 = injector.getInstance(TextEditor.class);
System.out.println(editor1.getSpellCheckerId());
}
}
class TextEditor {
private SpellChecker spellChecker;
@Inject
public void setSpellChecker(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public TextEditor() { }
public void makeSpellCheck() {
spellChecker.checkSpelling();
}
public double getSpellCheckerId() {
return spellChecker.getId();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).to(SpellCheckerImpl.class);
}
}
interface SpellChecker {
public double getId();
public void checkSpelling();
}
@Singleton
class SpellCheckerImpl implements SpellChecker {
double id;
public SpellCheckerImpl() {
id = Math.random();
}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
@Override
public double getId() {
return id;
}
}
ファイルをコンパイルして実行すると、同じ番号の次の出力が表示されます。
0.3055839187063575
0.3055839187063575
@Singletonアノテーションなしの結果
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
public class GuiceTester {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new TextEditorModule());
SpellChecker spellChecker = new SpellCheckerImpl();
injector.injectMembers(spellChecker);
TextEditor editor = injector.getInstance(TextEditor.class);
System.out.println(editor.getSpellCheckerId());
TextEditor editor1 = injector.getInstance(TextEditor.class);
System.out.println(editor1.getSpellCheckerId());
}
}
class TextEditor {
private SpellChecker spellChecker;
@Inject
public void setSpellChecker(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public TextEditor() { }
public void makeSpellCheck() {
spellChecker.checkSpelling();
}
public double getSpellCheckerId() {
return spellChecker.getId();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).to(SpellCheckerImpl.class);
}
}
interface SpellChecker {
public double getId();
public void checkSpelling();
}
class SpellCheckerImpl implements SpellChecker {
double id;
public SpellCheckerImpl() {
id = Math.random();
}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
@Override
public double getId() {
return id;
}
}
出力
次に、ファイルをコンパイルして実行します。 あなたは異なる番号で次の出力を見ることができます-
0.556007079571739
0.22095011760351602
Google Guice-AOP
AOP、アスペクト指向プログラミングは、プログラムロジックをいわゆる懸念と呼ばれる別個の部分に分解することを伴います。 アプリケーションの複数のポイントにまたがる機能は横断的関心事と呼ばれ、これらの横断的関心事はアプリケーションのビジネスロジックと概念的に分離されています。 ロギング、監査、宣言的トランザクション、セキュリティ、キャッシングなどの側面のさまざまな一般的な良い例があります。
OOPのモジュール性の重要な単位はクラスですが、AOPのモジュール性の単位は側面です。 依存性注入は、アプリケーションオブジェクトを相互に分離するのに役立ち、AOPは、影響を受けるオブジェクトから横断的な関心事を分離するのに役立ちます。 AOPは、Perl、.NET、Javaなどのプログラミング言語のトリガーのようなものです。 Guiceは、アプリケーションをインターセプトするインターセプターを提供します。 たとえば、メソッドの実行時に、メソッドの実行前または実行後に機能を追加できます。
重要なクラス
- Matcher -Matcherは、値を受け入れるか拒否するかのインターフェイスです。 Guice AOPでは、2つのマッチャーが必要です。1つは参加するクラスを定義するものであり、もう1つはそれらのクラスのメソッド用です。
- MethodInterceptor -MethodInterceptorsは、一致するメソッドが呼び出されたときに実行されます。 メソッド、引数、受信インスタンスなどの呼び出しを検査できます。 クロスカットロジックを実行してから、基になるメソッドに委任できます。 最後に、戻り値または例外を調べて戻ります。
例
GuiceTesterという名前のJavaクラスを作成します。
*GuiceTester.java*
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.matcher.Matchers;
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(SpellChecker.class).to(SpellCheckerImpl.class);
bindInterceptor(Matchers.any(),
Matchers.annotatedWith(CallTracker.class),
new CallTrackerService());
}
}
//spell checker interface
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
@Override @CallTracker
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
@interface CallTracker {}
class CallTrackerService implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Before " + invocation.getMethod().getName());
Object result = invocation.proceed();
System.out.println("After " + invocation.getMethod().getName());
return result;
}
}
出力
ファイルをコンパイルして実行すると、次の出力が表示される場合があります。
Before checkSpelling
Inside checkSpelling.
After checkSpelling