Below is an extremely lightweight dependency injection utility.

Purpose:

Minimal Dependencies: Currently uses only java.util, java.lang.reflect, and a ReflectUtils class.

Currently uses only java.util, java.lang.reflect, and a ReflectUtils class. Self-Constructing: When dependencies do not exist, AppContext attempts to construct dependencies upon request.

When dependencies do not exist, AppContext attempts to construct dependencies upon request. Multi-Context: Context is passed around, not dependencies. Switching context is as simple as using a different AppContext instance.

Context is passed around, not dependencies. Switching context is as simple as using a different AppContext instance. Simple: Avoid temptation to build all-the-things.

Potential Improvements:

Multiple Instances: If one needs two or more instances of a particular class, one could request a particular instance by it’s key. For example, “appContext.get(“someKey”, Color.class);” and “appContext.get(“someKey”, Font.class);” would actually retrieve different objects.

If one needs two or more instances of a particular class, one could request a particular instance by it’s key. For example, “appContext.get(“someKey”, Color.class);” and “appContext.get(“someKey”, Font.class);” would actually retrieve different objects. Separate Concerns: Storing/Retrieving and creating dependencies seems like separate concerns, suggesting this class can be split or functionality extracted to a more generic class.

Storing/Retrieving and creating dependencies seems like separate concerns, suggesting this class can be split or functionality extracted to a more generic class. Dependency-Swap: Conceptually, rather than returning the current instance, what could be returned is a wrapper for the given instance. The value-add is that if one wishes to replace the current instance, all references to that instance are also updated. The cost is likely to be in terms of performance, since each use would require a ‘get’ to retrieve the current instance.

Unit Tests: