Created
August 11, 2021 06:59
-
-
Save JSH32/e9e9538bdf98c471929d79d49ae1fd3d to your computer and use it in GitHub Desktop.
Basic dependency injection annotation framework with Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class DependencyNotFoundException extends Exception { | |
| public DependencyNotFoundException(String message) { | |
| super(message); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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