Servlet 3.0 容器中的外部过滤器和 Servlet 注入 CDI
我最终决定看看 Tomcat 中的 Weld。当我部署应用程序时,我在日志中看到:
“检测到 Tomcat 7,CDI 注入将在 Servlet 和 Filter 中可用”
例如,如何在 Filter/Servlet 外部使用 BeanManager 创建 bean 实例?
我有一个 bean:
@javax.inject.Named(value="CarService")
@javax.enterprise.context.RequestScoped
public class CarService implements Serializable{
.
.
.
并且我想使用 BeanManager 为指定的请求上下文创建它的实例。
Context ctx = new InitialContext();
BeanManager manager = (BeanManager) ctx.lookup("java:comp/env/BeanManager");
// NOW WHAT?
如果这可以在 servlet/filter 中完成,我确信它可以在其他任何地方完成,但我只是不想在不先询问的情况下浏览 Weld 代码并自己弄清楚。
非常感谢。
I finally decided to have a look at Weld in Tomcat. When I deploy my app I see in the log:
"Tomcat 7 detected, CDI injection will be available in Servlets and Filters"
How can for example create an instance of a bean using the BeanManager outside a Filter/Servlet?
I have a bean:
@javax.inject.Named(value="CarService")
@javax.enterprise.context.RequestScoped
public class CarService implements Serializable{
.
.
.
and I want to create an instance of it using the BeanManager for the specified request context.
Context ctx = new InitialContext();
BeanManager manager = (BeanManager) ctx.lookup("java:comp/env/BeanManager");
// NOW WHAT?
If this can be done in a servlet/filter I am sure it can be done anywhere else but I just do not want to go through the Weld code and figure it out myself without asking first.
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该很少使用 BeanManager 。重点是在需要依赖项的地方使用@Inject(即依赖注入)。使用管理器是“服务定位器”模式。
如果您确实需要它,请使用manager.getBeans(yourDesiredClass),然后从集合中选择一个并调用manager.getReference(bean, theClass, ctx)。
ctx
将通过manager.createCreationalContext(bean)
获得Using the
BeanManager
is something that you should rarely do. The point is to use@Inject
in places where you need dependencies (which is dependency injection). Using the manager is the "service-locator" pattern.If you really need it, use
manager.getBeans(yourDesiredClass)
, then pick one from the set and callmanager.getReference(bean, theClass, ctx)
.ctx
will be obtained bymanager.createCreationalContext(bean)
我已经使用了这个 Seam 代码,它给了我所需的一切。
I already used this Seam code which gave me all I needed.