How Guice Fills Annotated Fields

For my own education, I wanted to create a simple Injection Dependency infrastructure that works similar to how Google Guice does it. Thus, when the class is loaded, it pre-populates the annotated fields with data from the factory class.

I use Reflections to scan all my factory classes at compile time and store these classes in a static list, so when it comes time to load my classes, I have a link to my plants, which I can then scan and return the corresponding data.

Where am I stuck with how to pre-populate annotated class fields without actually doing any work in the current class. In other words, when the class is loading, I need to determine if any of the fields is annotated with a specific annotation, and if there are any, extract the value from the factory class.

Is there a way to reflect in a class before loading, pre-populate certain fields and then return an instance of this class to be used?

I could extend all my classes that require dependency injection with a base class that does all this work, but I believe there should be a better way so that I can just use @Inject (or some kind of annotation that I solve use to say that this field requires DI) and "magically" all the work is done.

+5
source share
1 answer

What Giis approaches is that it fills in the fields of the instance that Guice 1 itself created . After creating an instance, an injector can use the Reflection API to view fields Classand check their annotations with Field.getDeclaredAnnotations().

This is also the reason that when you want to type in a static field, you need to use Binder.requestStaticInjection()to populate static fields.

Guice doesn't just look at your annotation code; All injections are repeated from the explicit request (e.g. requestStaticInjection(), Injector.getInstance()etc). Now often this initial, explicit request will be made in some library code.

, guice-servlet, Guice serve().with(). web.xml, Guice .

1 - Binder.requestInjection().

+5

All Articles