diff --git a/src/dev/peerat/framework/DependencyInjector.java b/src/dev/peerat/framework/DependencyInjector.java index 6e25420..8276af4 100644 --- a/src/dev/peerat/framework/DependencyInjector.java +++ b/src/dev/peerat/framework/DependencyInjector.java @@ -8,16 +8,19 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; +import java.util.function.Supplier; public class DependencyInjector{ private Map map; + private Map, Supplier> suppliers; private List, Object>> builders; private Object[] injections; private Map, Object> cache; public DependencyInjector(){ this.map = new HashMap<>(); + this.suppliers = new HashMap<>(); this.builders = new ArrayList<>(); } @@ -31,6 +34,11 @@ public class DependencyInjector{ return this; } + public DependencyInjector of(Class type, Supplier supplier){ + this.suppliers.put(type, supplier); + return this; + } + public DependencyInjector of(Object... injections){ if(this.injections == null){ this.injections = injections; @@ -58,14 +66,23 @@ public class DependencyInjector{ public Object find(Injection annotation, Class type){ if(annotation != null){ Object result = this.map.get(annotation.value()); - if(result == null) throw new IllegalArgumentException("No depdency named "+annotation.value()+" ("+this.map.keySet()+")"); + if(result == null){ + Supplier supplier = this.suppliers.get(type); + if(supplier == null) throw new IllegalArgumentException("No dependency named "+annotation.value()+" ("+this.map.keySet()+")"); + result = supplier.get(); + this.map.put(annotation.value(), result); + } return result; } for(BiFunction, Object> function : builders){ Object result = function.apply(annotation, type); if(result != null) return result; } - if(this.injections == null) throw new IllegalArgumentException("No dependency for type "+type); + if(this.injections == null){ + Supplier supplier = this.suppliers.get(type); + if(supplier == null) throw new IllegalArgumentException("No dependency for type "+type); + return supplier.get(); + } Object result = this.cache.get(type); if(result != null) return result; for(Object injection : injections){ @@ -75,7 +92,11 @@ public class DependencyInjector{ result = injection; } } - if(result == null) throw new IllegalArgumentException("No dependency for type "+type); + if(result == null){ + Supplier supplier = this.suppliers.get(type); + if(supplier == null) throw new IllegalArgumentException("No dependency for type "+type); + return supplier.get(); + } return result; }