如何注入资源并在构造函数中使用
问题描述:
我想注入资源并使用它在带有roboguice注入的singleton类的构造函数中。下面是一个示例,显示我需要但注入字段在构造函数中为null。我正在阅读关于提供者的一些内容,并且为了获取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);
}
}
答
正如我所看到的阅读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。