com.github.henryco.injector.GrInjector Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of grinjector Show documentation
Show all versions of grinjector Show documentation
Lightweight reflective dependency injector for java.
package com.github.henryco.injector;
import com.github.henryco.injector.meta.ModuleStruct;
public final class GrInjector {
private static GrInjector ourInstance = new GrInjector();
private final Container container;
private GrInjector() {
container = new Container();
}
private void injectToTarget(Object dest) {
for (ModuleStruct module : container.modules) {
boolean inject = module.inject(dest);
if (inject) return;
}
throw new RuntimeException("There are no dependencies to inject " + dest.getClass());
}
private void injectToTarget(Object dest, String... components) {
for (ModuleStruct module : container.modules) {
boolean inject = module.inject(dest, components);
if (inject) return;
}
throw new RuntimeException("There are no dependencies to inject " + dest.getClass());
}
private void injectToTarget(Object dest, Class>... components) {
for (ModuleStruct module : container.modules) {
boolean inject = module.inject(dest, components);
if (inject) return;
}
throw new RuntimeException("There are no dependencies to inject " + dest.getClass());
}
private T getComponentByName(String name) {
for (ModuleStruct module : container.modules) {
T t = module.findOrInstanceByName(name);
if (t != null) return t;
}
return null;
}
private T getComponentByType(Class type) {
for (ModuleStruct module : container.modules) {
T t = module.findOrInstanceByType(type);
if (t != null) return t;
}
return null;
}
private void addRootModules(Class>... rootModules) {
container.addModules(rootModules);
}
private void resetModules() {
container.reset();
}
/**
* @param dest instance inject to
*/
public static void inject(Object dest) {
ourInstance.injectToTarget(dest);
}
/**
* @param dest instance inject to
* @param components desired components names
*/
public static void inject(Object dest, String ... components) {
ourInstance.injectToTarget(dest, components);
}
/**
* @param dest instance inject to
* @param components desired components types
*/
public static void inject(Object dest, Class> ... components) {
ourInstance.injectToTarget(dest, components);
}
public static void addModules(Class> ... rootModules) {
ourInstance.addRootModules(rootModules);
}
public static T getComponent(String name) {
return ourInstance.getComponentByName(name);
}
public static T getComponent(Class cmpClass) {
return ourInstance.getComponentByType(cmpClass);
}
/**
* Reset all modules with dependencies
*/
public static void reset() {
ourInstance.resetModules();
}
}