DependencyInjector -> Add method to provide a Supplier for a Type

This commit is contained in:
jeffcheasey88 2025-05-02 17:36:09 +02:00
parent dfeb611532
commit b77c6d120e

View file

@ -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<String, Object> map;
private Map<Class<?>, Supplier<?>> suppliers;
private List<BiFunction<Injection, Class<?>, Object>> builders;
private Object[] injections;
private Map<Class<?>, 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<Injection, Class<?>, 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;
}