[英]How do I get PicoContainer to start/stop/dispose a component injected by a factory?
[英]How do I manage dynamic dependencies with PicoContainer?
假设我有两个A和B类,B取决于A.
public class A {}
public class B {
public B(A a) {}
}
在单个PicoContainer中解析B很容易。
final MutablePicoContainer root = new PicoBuilder().build();
root.addComponent(new A());
root.addComponent(B.class, B.class);
System.out.println(root.getComponent(B.class));
但是我想为不同的会话设置不同的B
实例,其中包含A
变量实例。 我在考虑这样的事情。
// during startup
final MutablePicoContainer root = new PicoBuilder().build();
root.addComponent(B.class, B.class);
// later, initialize sessions
final MutablePicoContainer session = new PicoBuilder(root)
.implementedBy(TransientPicoContainer.class)
.build();
session.addComponent(new A());
// some request
System.out.println(session.getComponent(B.class));
上面的代码不起作用,因为在询问B
session
,它会询问父容器root
。 在那里找到B
,但只在root
及其父UnsatisfiableDependenciesException.
内解析,导致UnsatisfiableDependenciesException.
有没有什么好办法让这项工作成功? 或者这是一种反模式,我是以错误的方式解决问题的?
解决不存在的性能问题不是一个好方法。 你做过任何分析来验证问题吗?
如果没有,请考虑先做。
您是否在容器上启用了缓存(或者您使用的是Pico 1.x)?
尝试阅读此内容 ,可能禁用缓存足以解决此问题。
我也会在会话容器中注册B. B的任何其他依赖关系都可以留在根容器中。 假设B对C有另一个依赖关系。所以你可以做以下事情:
// during startup
final MutablePicoContainer root = new PicoBuilder().build();
root.addComponent(C.class, C.class);
// later, initialize sessions
final MutablePicoContainer session = new PicoBuilder(root)
.implementedBy(TransientPicoContainer.class)
.build();
session.addComponent(B.class, B.class);
session.addComponent(new A());
// some request
System.out.println(session.getComponent(B.class));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.