Skip to content

Instantly share code, notes, and snippets.

@JSH32
Created August 11, 2021 06:59
Show Gist options
  • Select an option

  • Save JSH32/e9e9538bdf98c471929d79d49ae1fd3d to your computer and use it in GitHub Desktop.

Select an option

Save JSH32/e9e9538bdf98c471929d79d49ae1fd3d to your computer and use it in GitHub Desktop.
Basic dependency injection annotation framework with Java
public class DependencyNotFoundException extends Exception {
public DependencyNotFoundException(String message) {
super(message);
}
}
/**
* Apply to a field to fill the field with a registered dependency.
* <p>
* If the InjectionContext cannot find the dependency and optional is disabled it will throw an exception on register
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Inject {
boolean optional() default false;
}
public class InjectionContext {
private final Map<Class<?>, Object> instanceMap = new IdentityHashMap<>();
public void registerDependency(Class<?> type, Object instance) {
instanceMap.put(type, instance);
}
/**
* Remove a dependency from the injection context. This will not affect already loaded objects
*
* @param type dependency type to remove
*/
public void removeDependency(Class<?> type) {
instanceMap.remove(type);
}
/**
* Gets all Inject fields of an object and fills the contents
*/
public void load(Object object) throws DependencyNotFoundException, IllegalAccessException {
for (Field field : object.getClass().getDeclaredFields()) {
if (!field.isAnnotationPresent(Inject.class)) continue;
Object instance = instanceMap.get(field.getType());
if (instance == null)
if (!field.getAnnotation(Inject.class).optional())
throw new DependencyNotFoundException(String.format("Non optional field %s on class %s annotated with Inject could not find an instance",
field.getName(), object.getClass().getName()));
field.setAccessible(true);
field.set(object, instance);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment