英文:
How to inject objects with list as an constructor argument using picocontainer?
问题
我有一个类,其构造函数接受一个列表参数:
public class A{
private List<B> bs;
public A(List<B> bs) {
this.bs = bs;
}
}
我将这个类添加到容器中,如下所示:
A a = someObject.createData();
pico.addComponent(a);
但是我得到了一个异常:
org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException: A has unsatisfied dependency 'java.util.List<B>' for constructor 'public A(java.util.List)' from org.picocontainer.DefaultPicoContainer@5b970f7:6<|
有人知道为什么会发生这种情况吗?
组合代码:
MutablePicoContainer pico = new DefaultPicoContainer();
SomeClass sc = new SomeClass();
A a = sc.createbData();
pico.addComponent(sc);
pico.addComponent("bs", a.getB());
pico.addComponent("a", A.class);
英文:
I have a class which takes an list argument in its contructor:
public class A{
private List<B> bs;
public A(List<B> bs) {
this.bs= bs;
}
}
And I am adding this class in the container as follows:
A a = someObject.createData();
pico.addComponent(a);
But I am getting an exception:
org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException: A has unsatisfied dependency 'java.util.List<B>' for constructor 'public A(java.util.List)' from org.picocontainer.DefaultPicoContainer@5b970f7:6<|
Does anyone know why this is happening?
Composition Code:
MutablePicoContainer pico = new DefaultPicoContainer();
SomeClass sc= new SomeClass();
A a = sc.createbData();
pico.addComponent(sc);
pico.addComponent("bs", a.getB());
pico.addComponent("a", A.class);
答案1
得分: 2
这个错误意味着在容器中没有注册类'B'。应该有类似以下的内容:
B b = new B();
pico.addComponent(b);
'B' 也可以是一个接口,而且 Picocontainer 支持带有依赖关系的数组注入,所以以下方式也可以工作:
public interface B {}
public class B1 implements B {}
public class B2 implements B {}
public class Test {
private List<B> stores;
public Test(List<B> stores) {
this.stores = stores;
}
}
pico.addComponent("b1", B1.class);
pico.addComponent("b2", B2.class);
pico.addComponent("test", Test.class);
还请查看官方的测试用例:https://github.com/picocontainer/picocontainer/blob/0f8172b7b12483920d0e3e2fcadb793d7ead4432/script/script-core/src/test/com/picocontainer/script/xml/XMLContainerBuilderTestCase.java#L868
英文:
This error means that you don't have class 'B' registered in container.
There should be something like:
B b = new B();
pico.addComponent(b);
'B' can be an interface too, and Picocontainer supports injection of arrays with dependencies, so this will work:
public interface B {}
public class B1 implements B {}
public class B2 implements B {}
public class Test {
private List<B> stores;
public Test(List<B> stores) {
this.stores=stores;
}
}
pico.addComponent("b1",B1.class);
pico.addComponent("b2",B2.class);
pico.addComponent("test",Test.class);
Check also an official test case: https://github.com/picocontainer/picocontainer/blob/0f8172b7b12483920d0e3e2fcadb793d7ead4432/script/script-core/src/test/com/picocontainer/script/xml/XMLContainerBuilderTestCase.java#L868
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论