2013-02-12 40 views
0

我有问题使用由Guice注入的工厂。如何使用Guice在Android中注入工厂?

我读过这篇不错的文章http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/assistedinject/FactoryModuleBuilder.html但还是不明白。即为什么模块从不使用?像在Guice.createInjector()方法。

我试过这个简单的应用程序,我有NullPointerException,因为Guice无法解决我需要的工厂。

public interface FooInterface 
{ 
    String getString(); 
} 

public class Foo implements FooInterface { 
    String bar; 

    @Inject 
    Foo(@Assisted String bar) 
    { 
     Log.i("main", "Foo constructor"); 
     this.bar = bar; 
    } 

    public String getString(){ 
     Log.i("main", "getString"); 
     return this.bar; 
    } 
} 

public interface FooFactory 
{ 
    FooInterface create(String bar); 
} 

下面是配置模块

public class ConfigurationModule extends AbstractModule 
{ 
    @Override 
    protected void configure() 
    { 
     Log.i("main", "Configuration module"); 
     install(new FactoryModuleBuilder().implement(FooInterface.class, Foo.class).build(FooFactory.class)); 
    } 
} 

我的活动

public class MyActivity extends Activity implements View.OnClickListener 
{ 
    @Inject private FooFactory fooFactory; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Log.i("main", "onCreate"); 

     Button btn = (Button) findViewById(R.id.btn); 
     btn.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View view) 
    { 
     Log.i("main", "onClick"); 
     FooInterface foo = this.fooFactory.create("foo name"); 
     String str = foo.getString(); 
     Toast.makeText(getApplicationContext(), "String is: "+ str, Toast.LENGTH_SHORT); 
    } 
} 

正如我可以看到日志,构造函数永远不会被调用。与ConfigurationModule相同。我看不到这个模块在哪里使用。有任何想法吗?也许我错过了什么?

+0

你在哪里安装ConfigurationModule?你如何创建MyActivity活动? (你发布的代码看起来是正确的,但是你确实需要确保你正在创建一个基于ConfigurationModule的注入器,并从中获取你的MyActivity实例。) – 2013-02-13 00:33:27

+0

这是我在任何示例中都找不到的问题我应该使用这个模块吗?所以基本上我根本不安装它,不知道该怎么做。 我没有创建活动。 Android的确如此。这是我使用应用程序启动的唯一活动。 – 2013-02-13 06:26:50

+1

我不认为你可以在Android上使用vanilla Guice。你看过:https://github.com/roboguice/roboguice/wiki? – condit 2013-02-13 18:39:57

回答

1

从我读过的所有内容中,我开始认为使用纯Guice for Android应用程序没有优势。 Roboguice是正确的选择。

0

如果您还需要使用ActionBarSherlock,请查看roboguice-sherlock

+0

是的,我知道这一点 – 2013-02-28 20:56:00