如何使用 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));
上面的代码不起作用,因为当向 session
请求 B
时,它会向父容器 root
请求它。 在那里找到了 B
,但仅在 root
及其父级中解析,导致 UnsatisfiableDependencyException。
有什么好的方法可以实现此功能吗? 或者这是一种反模式,而我正在以错误的方式解决问题?
Say I have two classes A and B, with B depending on A.
public class A {}
public class B {
public B(A a) {}
}
It's easy to resolve B in a single PicoContainer.
final MutablePicoContainer root = new PicoBuilder().build();
root.addComponent(new A());
root.addComponent(B.class, B.class);
System.out.println(root.getComponent(B.class));
But I'd like to have different instances of B
for different sessions, with variable instances of A
. I'm thinking about something like this.
// 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));
Above code isn't working, because when asking session
for a B
it asks the parent container root
for it. B
is found there, but resolved only within root
and its parents, leading to an UnsatisfiableDependenciesException.
Is there any good way to make this work? Or is this an anti-pattern, and I'm solving the problem in the wrong way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我也会在会话容器中注册 B。 您可以将 B 的任何其他依赖项保留在根容器中。 假设 B 对 C 有另一个依赖项。因此您可以执行以下操作:
I would register B within the session container as well. Any other dependency of B you can leave in the root container. Assume B has another dependency on C. So you can do the following:
解决不存在的性能问题并不是一个好方法。 您是否进行过任何分析来验证问题?
如果没有,请考虑先这样做。
Solving a performance problem that doesn't exist isn't a good approach. Have you done any profiling to verify the problem?
If not, consider doing that first.
您是否在容器上启用了缓存(或者您是否使用 Pico 1.x)?
尝试阅读这个,也许禁用缓存就足以解决这个问题。
Did you enable caching on your container (or are you using Pico 1.x)?
Try reading this, maybe disabling the cache is enough to solve this problem.