0

I have problem using Factory injected by Guice.

I've read this nice article http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/assistedinject/FactoryModuleBuilder.html but still don't understand something. I.e. why does Module never used? Like in Guice.createInjector() method.

I tried this simple application and I have NullPointerException, because Guice couldn't resolve Factory I need.

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);
}

Here is configuration Module

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));
    }
}

And my Activity

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);
    }
}

As I can see from logs, Foo constructor is never called. The same with ConfigurationModule. I can't see where this module is used. Any ideas? Maybe I'm missing something?

4

2 回答 2

1

从我读过的所有内容来看,我开始认为将纯 Guice 用于 Android 应用程序没有任何优势。Roboguice是正确的选择。

于 2013-02-14T06:36:57.960 回答
0

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

于 2013-02-28T14:30:39.820 回答