Skip to content

Instantly share code, notes, and snippets.

@sarxos
Last active March 14, 2019 12:00
Show Gist options
  • Select an option

  • Save sarxos/cc38514371def7587c0c50858d9dfc4c to your computer and use it in GitHub Desktop.

Select an option

Save sarxos/cc38514371def7587c0c50858d9dfc4c to your computer and use it in GitHub Desktop.
JustInTimeInjectionResolver will try resolve injectee when other injection attempts failed
// You should take care when using the above resolver as it'll add things into
// your ServiceLocator that you might not have been expecting. It will also
// probably not do well with injecting things like Strings or other types like
// that. Still, might work for your use case.
// Will not work if your injection point is injecting an interface!
@Singleton
@Visibility(DescriptorVisibility.LOCAL)
public class GreedyResolver implements JustInTimeInjectionResolver {
private final ServiceLocator locator;
@Inject
private GreedyResolver(ServiceLocator locator) {
this.locator = locator;
}
@Override
public boolean justInTimeResolution(Injectee failedInjectionPoint) {
Type type = failedInjectionPoint.getRequiredType();
if (type == null) return false;
Class<?> clazzToAdd = null;
if (type instanceof Class) {
clazzToAdd = (Class<?>) type;
}
else if (type instanceof ParameterizedType) {
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class) {
clazzToAdd = (Class<?>) rawType;
}
}
if (clazzToAdd == null) return false;
if (clazzToAdd.isInterface()) return false;
ServiceLocatorUtilities.addClasses(locator, clazzToAdd);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment