【问题标题】:How to inject resource and use it in the constructor如何在构造函数中注入资源并使用它
【发布时间】:2014-10-09 11:20:40
【问题描述】:

我想通过 roboguice 注入注入资源并在单例类的构造函数中使用它。下面是一个显示我需要的示例,但在构造函数中注入的字段为空。我正在阅读有关提供程序的内容,并过度考虑了另一个用于获取 url 的特殊类,但我不确定它是否是方便的解决方案。代码如下:

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

【问题讨论】:

    标签: java android dependency-injection retrofit roboguice


    【解决方案1】:

    正如我在阅读 Roboguice 文档时看到的,Roboguice 框架仅适用于 Android 编程。请参阅以下link

    在 Activity 中调用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 2018-03-27
      • 2015-12-10
      • 2014-02-23
      • 1970-01-01
      相关资源
      最近更新 更多