使用AndroidAnnotations注入静态@Bean时的NPE

时间:2017-05-24 12:05:58

标签: java android dependency-injection static android-annotations

我正在尝试使用AndroidAnnotations中的@Bean注入静态字段:

@EBean
public class LogUtil {

    @Bean(CrashReporting.class) static Reporting reporting;

    public static void log(Activity activity, String method) {
        reporting.log(activity.getClass().getName() + ":" + method);
    }

}

...

@EBean(scope = EBean.Scope.Singleton)
public class CrashReporting implements Reporting {

    @Override
    public void log(String text) {
        Log.d(getClass().getName(), text);
    }

}

reporting字段在运行时为空:

Caused by: java.lang.NullPointerException: 
Attempt to invoke interface method 
'void com.example.staticinjection.Reporting.log(java.lang.String)' 
on a null object reference
    at com.example.staticinjection.LogUtil.log(LogUtil.java:15)
    at com.example.staticinjection.MainActivity.onCreate(MainActivity.java:12)
    at android.app.Activity.performCreate(Activity.java:6237)
    ...

演示项目

1 个答案:

答案 0 :(得分:0)

注入的字段仅在调用@AfterInject带注释的方法后才可用。你是否在那之后访问了该领域?

编辑:你不能真正使用静电注入。您必须将bean注入Activity的实例成员:

@EActivity
public class MainActivity extends AppCompatActivity {

    @Bean
    LogUtil logger;

    @AfterInject
    public void afterInject() {
        logger.log(this, "AFTERINJECT");
    }
}

@EBean
public class LogUtil {

    @Bean(CrashReporting.class) Reporting reporting;

    public void log(Activity activity, String method) {
        reporting.log(activity.getClass().getName() + ":" + method);
    }

}