注入与托管属性 [英] Inject vs ManagedProperty

查看:122
本文介绍了注入与托管属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个JSF支持bean,它需要引用另一个(@NoneScoped)bean.

Okay, so I have a JSF backing bean that needs a reference to another (@NoneScoped) bean.

我应该@Inject它还是使用@ManagedProperty从容器中获取实例引用?

Should I @Inject it or use @ManagedProperty to obtain an instance reference from the container?

为什么要使用一种方法而不是另一种方法,在我看来,这两种方法可以实现相同的目的.

Why use one and not the other, in my mind the two approaches achieve the same thing.

推荐答案

@ManagedProperty@NoneScoped来自JSF 2.0规范,而@Inject来自CDI规范.

@ManagedProperty and @NoneScoped comes from the JSF 2.0 spec whilst @Inject comes from the CDI spec.

如果您仅在不使用任何其他JavaEE 6功能的servlet应用程序上工作,请使用@ManagedProperty.该注释相对于@Inject也有一个优势:您可以将其与EL(表达式语言)一起使用(

If you are just working on a servlet application that doesn't make any use of any of the others JavaEE 6 features, then go for @ManagedProperty. That annotation has also an advantage against @Inject: you can use EL (expression language) with it (although there are workarounds to get that in CDI).

两个注解/容器似乎都实现了"同一件事",但是方式却大不相同,并且它们可用于不同的容器.由CDI管理的Bean将可用于JSF,反之亦然.如果您要使用JSF特定的注释对bean进行注释,那么请不要使用自定义限定符,拦截器,生产者方法等.我通常更喜欢使用CDI的方法,因为最终它会更复杂,但是选择将取决于您的实际需求. .

Both annotations/containers seem to achieve "the same thing" but in very different ways and they work with different containers. Beans managed by CDI will be available to JSF but not viceversa. If you are annotating your beans with JSF specific annotations then forget about using custom qualifiers, interceptors, producer methods, etc. I usually prefer the approach with CDI because, at the end, it is more sophisticated but the choice will depend on your actual needs.

将其包装起来,似乎您只是在使用JSF功能,然后坚持使用@ManagedProperty (CDI无法理解@NoneScoped注释,在CDI中,所有bean都位于@Default范围(如果未指定).在项目中切换到CDI可能意味着不仅要用@ManagedProperty代替@Inject,还要用所有@RequestScoped(依此类推)代替专用于CDI的项目.

Wrapping it up, as it seems that you are just using JSF features then stick to the @ManagedProperty (CDI can't understand @NoneScoped annotations, in CDI all beans are under the @Default scope if none specified). Switching to CDI in your project might mean to replace not just the @ManagedProperty for an @Inject one, but all your @RequestScoped (and so on) for the CDI-specific ones.

这篇关于注入与托管属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆