Guice Injection入Google Cloud Endpoints Transformer

时间:2015-06-15 09:42:07

标签: java google-app-engine guice google-cloud-endpoints

我已成功使用Google Cloud Endpoints应用程序working with Guice

我希望将一个Singleton注入Api Transformer

假设我希望将Something转换为SomethingElse,其中Something声明它是变换器:

import com.google.api.server.spi.config.Transformer;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class MyApiTransformer
    implements Transformer<Something, SomethingElse> {

private MySingleton singleton;

@Inject
public MyApiTransformer(MySingleton singleton) {
    this.singleton = singleton;
}
@Override
public Something transformFrom(SomethingElse somethingElse) {
    return singleton.something(somethingElse);
}

@Override
public SomethingElse transformTo(Something something) {
    return singleton.somethingElse(something);
}

}

请注意,我希望将转换委托给我的Guice单例。当我尝试上述变压器时,我收到以下错误:

  

java.io.IOException:com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException:无法实例化自定义序列化程序MyApiTransformer,未找到构造函数:[(interface java.lang.reflect.Type), (类java.lang.Class),()]

似乎Guice没有提供ApiTransformers,所以杰克逊不知道如何在没有默认构造函数的情况下实例化该类。

Guice如何将Singleton注入ApiTransformer?

1 个答案:

答案 0 :(得分:0)

为您的Transformer提供默认构造函数并执行静态注入:

import com.google.api.server.spi.config.Transformer;
import com.google.inject.Inject;

public class MyApiTransformer
    implements Transformer<Something, SomethingElse> {

@Inject
private static MySingleton singleton;

public MyApiTransformer() {

}
@Override
public Something transformFrom(SomethingElse somethingElse) {
    return singleton.something(somethingElse);
}

@Override
public SomethingElse transformTo(Something something) {
    return singleton.somethingElse(something);
}

}

在你的模块中:

public class MyModule
    extends AbstractModule {

@Override
protected void configure() {

    requestStaticInjection(MyApiTransformer.class);
}

}