问题描述
我的基础 POJO 类:
public class BaseDao { public BaseDao() { } // ... }
我的扩展POJO类:
public class KelvinDao extends BaseDao { public KelvinDao () { super(); } // ... }
我想在这样的服务中使用 KelvinDao:
public class HanKelvinHandler extends HttpRequestHandler { @Inject private KelvinDao mKelvinDao; public void treatGet() { mKelvinDao.blabla(); !!! mKelvinDao is always NULL }
这真的很简单,但它不起作用:(
谢谢大家的帮助!
推荐答案
你是如何创建 HanKelvinHandler 的?如果您在 RoboGuice 类的子类中执行此操作,例如 RoboActivity,那么它应该可以正常工作.示例:
public class MyActivity extends RoboActivity { @Inject private HanKelvinHandler m_handler; [...] }
否则(即,您在另一个 POJO 中创建它),您在常规 Guice 领域,我相信您将需要使用注入器来获取它的实例.示例:
public class MyClass { public void doSomething() { Injector injector = Guice.createInjector( new YourGuiceBindings() ); HanKelvinHandler handler = injector.getInstance( HanKelvinHandler.class ); handler.treatGet(); // mKelvinDao should be good now } }
如果你之前没有见过注入器的使用,或者你不知道给 YourGuiceBindings() 放什么,那么你可能需要阅读以下内容:
https://github.com/roboguice/roboguice/wiki/Simple-自定义绑定
https://code.google.com/p/google-guice/维基/入门
似乎应该有一种方法可以在不使用注射器的情况下做到这一点,但我不知道.
问题描述
My base POJO class:
public class BaseDao { public BaseDao() { } // ... }
My extends POJO class:
public class KelvinDao extends BaseDao { public KelvinDao () { super(); } // ... }
I want to use KelvinDao in a service like that:
public class HanKelvinHandler extends HttpRequestHandler { @Inject private KelvinDao mKelvinDao; public void treatGet() { mKelvinDao.blabla(); !!! mKelvinDao is always NULL }
It's really simple but it doesn't work :(
Thank you guys for your help!
推荐答案
How are you creating HanKelvinHandler? If you're doing it within a subclass of a RoboGuice class, such as RoboActivity, then it should just work. Example:
public class MyActivity extends RoboActivity { @Inject private HanKelvinHandler m_handler; [...] }
Otherwise (i.e., you're creating it within another POJO), you're in regular Guice land, and I believe you will need to use the injector to get an instance of it. Example:
public class MyClass { public void doSomething() { Injector injector = Guice.createInjector( new YourGuiceBindings() ); HanKelvinHandler handler = injector.getInstance( HanKelvinHandler.class ); handler.treatGet(); // mKelvinDao should be good now } }
If you haven't seen the use of the injector before, or you don't know what to put for YourGuiceBindings(), then you may need to read the following:
https://github.com/roboguice/roboguice/wiki/Simple-Custom-Binding
https://code.google.com/p/google-guice/wiki/GettingStarted
It seems like there should be a way to do this without using the injector, but I don't know.