excilys/androidannotations — Issue #63: Support for Singleton scope
Author: pyricau
Created: 2012-01-14 15:43:26+00:00
State: open
Labels: Enhancement

Right now, our enhanced classes (`@Enhanced`) are short lived (something called "prototype scope" by Spring).

Each `@Inject` annotation leads to the creation of a new instance.

We could add support for singleton scope on `@Enhanced` beans, with a few simple changes in the generated code.

This :
```java
public class CustomBean_ extends CustomBean {

public CustomBean getInstance(Context context) {
return new CustomBean_(context);
}

}
```

Would become this :

```java
public class CustomBean_ extends CustomBean {

private static CustomBean instance;

public CustomBean getInstance(Context context) {
if (instance == null) {
instance = new CustomBean_(context.getApplicationContext());
}
return instance;
}

}
```
A few notes:

* We do not care about thread safety. Beans are meant to be created on the main thread.
* `context.getApplicationContext()` is important. We do not want to leak any context. This also means that annotations relying on specific contexts would not work. This would mean discarding @ViewById, @Click, etc... Is that OK ?

Should we create a new `@EnhancedSingleton` annotation instead of `@Enhanced` ? Or create an additional
`@Singleton` annotation that would be added to `@Enhanced` ? Or it could even be an annotation parameter, such as `@Enhanced(singleton=true)`.

Ideas welcome!