2017-11-22 11 views
1

私はGuiceで新しく、AssistedInjectを理解しようとしています。 私は非常に単純なプロジェクトがあります:私は注入したいGuiceは注射を助けました

クラス:アシスト射出と

public class I1 { 
} 

クラス:

public interface ICla { 
} 

public class Cla implements ICla{ 
    public Integer t; 
    public I1 i; 

    @Inject 
    public Cla(Integer t, @Assisted I1 i) { 
     this.t = t; 
     this.i = i; 

    } 
} 

工場

public interface IClaFactory { 
    Cla create(Integer t); 
} 

、メインクラス:

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

     IClaFactory factory = injector.getInstance(IClaFactory.class); 
    } 

    private static class Module extends AbstractModule { 
     protected void configure() { 
      install(new FactoryModuleBuilder() 
       .implement(ICla.class, Cla.class).build(IClaFactory.class)); 
     } 
    } 
} 

しかし、まだ動作しません、私は間違っている、私は理解していない?

Exception in thread "main" com.google.inject.CreationException: Unable to create injector, see the following errors: 

1) No implementation for ru.test.factory.I1 annotated with @com.google.inject.assistedinject.Assisted(value=) was bound. 
    while locating ru.test.factory.I1 annotated with @com.google.inject.assistedinject.Assisted(value=) 
    for parameter 1 at ru.test.factory.Cla.<init>(Cla.java:11) 
    at ru.test.factory.IClaFactory.create(IClaFactory.java:1) 
    at com.google.inject.assistedinject.FactoryProvider2.initialize(FactoryProvider2.java:660) 
    at com.google.inject.assistedinject.FactoryModuleBuilder$1.configure(FactoryModuleBuilder.java:335) (via modules: ru.test.Main$Module -> com.google.inject.assistedinject.FactoryModuleBuilder$1) 

2) Could not find a suitable constructor in java.lang.Integer. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private. 
    at java.lang.Integer.class(Integer.java:52) 
    while locating java.lang.Integer 
    for parameter 0 at ru.test.factory.Cla.<init>(Cla.java:11) 
    at ru.test.factory.IClaFactory.create(IClaFactory.java:1) 
    at com.google.inject.assistedinject.FactoryProvider2.initialize(FactoryProvider2.java:660) 
    at com.google.inject.assistedinject.FactoryModuleBuilder$1.configure(FactoryModuleBuilder.java:335) (via modules: ru.test.Main$Module -> com.google.inject.assistedinject.FactoryModuleBuilder$1) 

答えて

2

あなたは間違ったパラメータを-ing @Assistedだ:と「支援」するためのパラメータは、ファクトリインタフェースで定義されたパラメータです。この場合は、お客様のではなく、I1です。

これは動作します:

@Inject 
public Cla(I1 i, @Assisted Integer t) { 
    this.t = t; 
    this.i = i; 

} 
+0

は、それは私の問題を解決しました。私はGuiceが私のために@アシストしたと思ったが、実際には私はguiceが私の助けを必要としていた: – Andrew

+0

@Andrew私はあなたの問題を売却してうれしい。それがあったので、この回答を受け入れたと思いますか?答えのポイントの下にあるチェックマークをクリックしています。ありがとう;-) –