Guice注入和RequestFactory:扩展ServiceLayerDecorator
我搜索了一个将 Guice 依赖注入与 RequestFactory
一起使用的解决方案。 我偶然发现了这个: https://github.com/etiennep
它对我不起作用,所以我改变了InjectedServiceLayerDecorator.java 实现如下:
现在我的问题是:
关于 RequestFactory
的缓存机制是否可以做得更好(它仍然有效吗?)? getTop()
和 getNext()
(在 ServiceLayerDecorator 中)的用途是什么? 在这个地方使用 getTop() 是否正确/安全?
抱歉想得太复杂了! 这很简单:
Class<?> serviceClazz = resolveServiceClass(requestContext);
return injector.getInstance(serviceClazz);
I searched for a solution to use Guice Dependency injection together with RequestFactory
.
I stumbled upon this: https://github.com/etiennep
It wasn't working for me so I changed the InjectedServiceLayerDecorator.java implementation to this:
Now my questions are:
Can something be done better regarding the caching mechanism of RequestFactory
(Is it still working?)?
What is getTop()
and getNext()
(in ServiceLayerDecorator) for?
And is it correct / safe to use getTop()
in this place?
Sorry thought too complicated!
It was as easy as:
Class<?> serviceClazz = resolveServiceClass(requestContext);
return injector.getInstance(serviceClazz);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ServiceLayer 使用责任链模式:如果您的装饰器没有什么具体要做的事情,它应该通过使用相同的参数调用相同的方法来委托给链中的下一个装饰器(由
getNext
返回)。如果您的装饰器更改了参数,或者需要调用另一个方法,它应该在getTop
上调用它,以便调用通过所有装饰器进行路由,而不仅仅是链中自身之后的装饰器。因此,您对 getTop 的使用是正确且安全的(看看 GWT 中的 LocatorServiceLayer,这正是它的作用)。
但您的代码(以及 Etienne 的代码!)实际上可以变得更简单、更好:只需覆盖
createServiceLocator
即可从注入器获取一个实例(与createLocator
相同)。ServiceLayer uses a chain of responsibility pattern: in cases your decorator has nothing specific to do, it should delegate to the next decorator in the chain (returned by
getNext
) by calling the same method with the same arguments. If your decorator changes the arguments, or needs to call another method, it should call it ongetTop
so the call is routed through all decorators, and not just the ones after itself in the chain.Your use of
getTop
is thus correct and safe (have a look at the LocatorServiceLayer from GWT, that's exactly what it does).But your code (and Etienne's one!) can actually be made simpler and better: simply override
createServiceLocator
to get an instance from your injector (same ascreateLocator
).