0

I am using androidannotations in an Android project and I have an EBean defined as:

@EBean(scope = Singleton)
class MyBean {
    public void someFunction() {
    }
}

This bean is created whenever it is first required, that is, whenever I have:

@Bean
MyBean myBean;

in some class. I am also using EventBus in this project, and a function in MyBean is a @Subscriber. This function is not called (when an Event is posted) because an instance of MyBean does not exist (since I don't have the dependency anywhere). How can I create an instance of MyBean without specifically adding the dependency anywhere?

My temporary solution is to simply define the bean in my Application class.

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Vedavyas Bhat
  • 2,068
  • 1
  • 21
  • 31

2 Answers2

0

I think you're doing it the cleanest way possible. Have your CustomApplication class include @Bean MyBean myBean, even if it never calls a function on it. With AA and event bus subscriber classes, this is the only solution I have found.

The class needs to be instantiated somewhere. Since it's a singleton, it seems cleanest to do it in the CustomApplication class. An alternative might be to make the class a Service (in the Android sense - "extends Service"), which would let you declare it in your AndroidManifest.xml file. But since you don't require any Android service functionality, this seems like the wrong way to go about it.

clay_to_n
  • 583
  • 3
  • 15
0

Turns out, you can't create an EBean without injecting it somewhere. Refer this issue: https://github.com/excilys/androidannotations/issues/1692

My solution is to have a class EBeanManager (which is also an EBean) which simply injects the beans I need created. EBeanManager is injected into my Application class. The reason I'm doing it in a separate class is to avoid clutter in my Application class.

Vedavyas Bhat
  • 2,068
  • 1
  • 21
  • 31