如何在 GWT 应用程序中集成 dagger2?

How to integrate dagger2 in GWT application?

我正在尝试在我的 gwt 应用程序中添加 dagger2 以获得 DI。到目前为止,我已遵循以下步骤

1) 在 pom.xml

中添加了以下依赖项
    <dependency>
        <groupId>com.google.dagger</groupId>
        <artifactId>dagger-gwt</artifactId>
        <version>2.4</version>
    </dependency>

    <dependency>
        <groupId>com.google.dagger</groupId>
        <artifactId>dagger-compiler</artifactId>
        <version>2.4</version>
    </dependency>

    <dependency>
        <groupId>com.google.auto.factory</groupId>
        <artifactId>auto-factory</artifactId>
        <version>1.0-beta3</version>
    </dependency>

2) 通过添加以下代码行继承 gwt 模块 MyApp.gwt.xml 中的 dagger 依赖性。

<inherits name="dagger.Dagger" />

3) 创建组件 Class.

import javax.inject.Singleton;
import com.google.gwt.event.shared.EventBus;
import dagger.Component;

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {

    EventBus eventBus();
}

4) 创建模块 class

import javax.inject.Singleton;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;

import dagger.Module;
import dagger.Provides;

@Module
public class AppModule {

    @Provides
    @Singleton
    SimpleEventBus provideSimpleEventBus() {
        return new SimpleEventBus();
    }

    @Provides
    EventBus provideEventBus(SimpleEventBus bus) {
        return bus;
    }
}

最后,当我尝试在 AppEntryPoint

中构建模块时
AppComponent component = DaggerAppComponent.builder()....build();

我在 mvn compilemvn gwt:compile 之后的任何地方都找不到生成的 class DaggerAppComponent。我正在使用 org.codehaus.mojo 中的 gwt-maven-plugin。很明显我在配置中遗漏了一些东西,但无法弄清楚到底是什么。

首先,您需要确保注释处理器是由maven-compiler-plugin 触发的。我强烈建议使用 maven-compiler-plugin 的 3.5.1(至少)版本,它修复了一些问题,这些问题使得在 Maven 中使用注释处理器变得非常不切实际。
使用默认配置,源代码将在 target/generated-sources 中生成并添加为项目源代码,以便稍后 gwt-maven-plugin 可以正确获取它们。

您应该将 dagger-compiler 依赖项更改为 <optional>true</optional><scope>provided</scope>;甚至更好,在 maven-compiler-plugin 的 annotationProcessorPath 中声明它。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.5.1</version>
    <configuration>
        <source>1.7</source>
        <target>1.7</target>
        <annotationProcessorPaths>
            <path>
                <groupId>com.google.dagger</groupId>
                <artifactId>dagger-compiler</artifactId>
                <version>${dagger.gwt.version}</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

对于开发模式,每次对已处理的 类 进行更改时,都需要重新 运行 注释处理器;这通常由您的 IDE 完成,但可以使用 mvn compilemvn process-classes.

从命令行触发

您可以在我的 gwt-maven-archetypes

中看到完整的设置