IOC - Google ガイド

Google Guice は、依存関係注入と IoC に重点を置いた軽量の依存関係注入フレームワークであり、中小規模のアプリケーションに適しています。
Spring Framework は、幅広い機能を提供し、大規模なエンタープライズ アプリケーションに適した包括的なエンタープライズ レベルのフレームワークです。

そうです! IOC コンテナは Spring だけでなく、Google Guice も使用できます。体験してみましょう:
まず、ステップ 0 は Maven の依存関係を追加することです:

<dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>4.2.3</version> <!-- 使用适当的版本号 -->
</dependency>

ステップ 1: インターフェースおよび実装クラスを作成する

まず、インターフェイスと実装クラスを作成します。

// Service接口
public interface Service {
    void execute();
}

// Service的实现类
public class MyService implements Service {
    @Override
    public void execute() {
        System.out.println("MyService 执行了.");
    }
}

ステップ 2: Guice モジュールを作成する

次に、依存関係を管理するように構成された Guice コンテナーを含む Guice モジュールを作成します。このモジュールでは、インターフェイスと実装クラスをバインドします。

import com.google.inject.AbstractModule;

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Service.class).to(MyService.class);
    }
}

ステップ 3: Guice コンテナーを使用する

ここで、Guice コンテナを使用して依存関係を作成し、注入します。

import com.google.inject.Guice;
import com.google.inject.Injector;

public class DemoLfsunStudyGuiceApplication {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new MyModule());

        // 请求Guice容器提供Service实例
        Service service = injector.getInstance(Service.class);

        // 使用Service
        service.execute();
    }
}

ここに画像の説明を挿入します

Guice コンテナを作成し、MyModule を使用して依存関係を構成します。次に、Guice コンテナは、injector.getInstance(Service.class) を通じて Service インターフェイスのインスタンスを提供するように要求され、最後に execute メソッドが呼び出されます。

おすすめ

転載: blog.csdn.net/qq_43116031/article/details/134308779