I'm trying to dynamically retrieve a dependency for my Java code.
I know the class name, but I want to take the instance managed by the container, with proper indirect dependencies resolved.
For example:
class Foo {
public static void foo() {
Bar bar = (Bar) getDependency("com.example.Bar");
bar.bar();
}
}
class Bar {
@Inject
private Spam spam;
public void bar() {
spam.spam();
}
}
I can't construct a Bar
instance myself because I wouldn't be able to inject the correct Spam
. So I want as if Foo
had injected a Bar
into it. I can't add a field like @Inject Bar bar
because the exact name of the dependency varies in runtime.
Any way to do this?
I'm using WildFly 8.2.0.
You can do something like this:
public class Foo {
@Inject BeanManager beanManager;
public void foo() {
Set<Bean<?>> beans = beanManager.getBeans(Bar.class);
Bean<?> bean = beanManager.resolve(beans);
CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
Bar bar = (Bar) beanManager.getReference(bean, Bar.class, creationalContext);
}
}
or maybe even simpler:
public class Foo {
@Inject Instance<Object> instance;
public void foo() {
Bar bar = instance.select(Bar.class).get();
}
}