如何注入资源并在构造函数中使用它

时间:2014-10-09 11:20:41

标签: java android dependency-injection retrofit roboguice

我想注入资源并使用roboguice注入在singleton类的构造函数中使用它。下面的示例显示了我需要的内容,但在构造函数中,inject field为null。我正在阅读关于提供者的一些内容,并且想要获取另一个特殊课程以获取网址,但我不确定它是否是方便的解决方案。代码如下:

@Singleton
public class ProductService implements IProductService {

    @InjectResource(R.string.server_url)
    private String serverBaseUrl;

    IProductAPI productAPI;

    public ProductService() {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(serverBaseUrl)
                .build();
        productAPI = restAdapter.create(IProductAPI.class);
    }

    public ProductDTO retrieveProductByEan(String productEan) throws RetrofitError {
        return productAPI.getProductByEan(productEan);
    }
}

1 个答案:

答案 0 :(得分:0)

正如我所看到的阅读Roboguice文档,Roboguice框架只考虑Android编程。请参阅以下link

在活动中调用 super.onCreate()方法时进行注射。

以下是github中完整示例的代码的一部分:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // @Inject, @InjectResource, and @InjectExtra injection happens during super.onCreate()

        sayText.setOnEditorActionListener(new OnEditorActionListener() {
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {

                // Have the remoteControl tell Astroboy to say something
                remoteControl.say(textView.getText().toString());
                textView.setText(null);
                return true;
            }
        });

所以我建议使用静态值来引用 serverBaseUrl