【问题标题】:Using a compile-time environment variable to configure RestApplicationPath使用编译时环境变量来配置 RestApplicationPath
【发布时间】:2014-09-01 03:44:12
【问题描述】:

rest-dispatch的文档所述,其余应用路径必须通过常量在GIN模块中配置,此处为“/api/v1”:

public class DispatchModule extends AbstractGinModule {
   @Override
   protected void configure() {
       RestDispatchAsyncModule.Builder dispatchBuilder = 
               new RestDispatchAsyncModule.Builder();
       install(dispatchBuilder.build());
       bindConstant().annotatedWith(RestApplicationPath.class).to("/api/v1");   
   }
}

我想在编译时解析“/api/v1”常量,基于构建系统根据目标环境(prod、dev 等)设置的环境变量,以及其他标准(构建工件主要版本...)。

问题是我无法依赖编译时变量。 TextResource/CssResource 和 GWT 的 deferred binding 在这里都无济于事,因为 GWT.create() 不能在 GIN 模块中使用。我考虑的另一个选择是使用自定义生成器,但这对于这个非常简单的需求来说似乎太复杂了。

你是怎么解决这个问题的?

【问题讨论】:

  • 你的构建系统使用 Maven 吗?

标签: java gwt gwtp gwt-platform gwt-gin


【解决方案1】:

按照 Thomas Broyer 的建议和 Simon-Pierre,您甚至可以根据您的 maven 配置文件绑定不同的根 .gwt.xml 文件。然后选择绑定常量的适当 Gin 模块类。

这就是我们在 GWTP 的 CarStore 配套项目中所做的,例如做 Form factor。

【讨论】:

    【解决方案2】:

    您没有理由不能用 @Provides 方法(或其他 bind().toProvider(),这将允许您使用 TextResource 和/或延迟绑定或其他方法)替换 bindConstant()

    作为一个示例(尽管未经测试),下面的代码使用 JSNI 从主机页面读取值,这使其依赖于运行时(而不是编译时):

    @Provides @RestApplicationPath native String provideRestApplicationPath() /*-{
      return $wnd.restApplicationPath;
    }-*/;
    

    【讨论】:

      【解决方案3】:

      如果您使用 Maven 作为构建系统,您可以利用 templating-maven-plugin 生成一个 Java 类,该类将包含在您的 POM 文件中定义的静态变量。您的 GWT 代码将使用该生成的类。

      例如,您可能想要填充 BuildConstants 类模板

      public class BuildConstants {
        // will be replaced by Maven
        public static final String API_VERSION  = "${myapi.version}";
      }
      

      并使用 Maven 属性:

      <myapi.version>v1</myapi.version>
      

      将被编译为

      public class BuildConstants {
        // will be replaced by Maven
        public static final String API_VERSION  = "v1";
      }
      

      您可以在 DispatchModule 中引用这些常量:

      bindConstant().annotatedWith(RestApplicationPath.class).to("/api/" + BuildConstants.API_VERSION);   
      

      这是我在项目中使用的模板 maven-plugin 的示例配置:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>templating-maven-plugin</artifactId>
        <version>1.0-alpha-3</version>
        <executions>
          <execution>
            <id>filter-src</id>
            <goals>
              <goal>filter-sources</goal>
            </goals>
            <configuration>
              <sourceDirectory>${basedir}/src/main/java-templates</sourceDirectory>
              <outputDirectory>${project.build.directory}/generated-sources/java-templates
              </outputDirectory>
            </configuration>
          </execution>
         </executions>
      </plugin>
      

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-18
        • 2017-08-11
        • 1970-01-01
        • 1970-01-01
        • 2014-05-14
        相关资源
        最近更新 更多