获取对其他托管 Bean 的引用的惯用方法是什么?
在我看来,可以通过三种方式获取对另一个 bean 的引用:
- 使用 CDI,我可以
@Inject
命名 bean。这样做的缺点是 CDI 注释与面孔注释不能很好地混合,因此我不能再使用@ViewScoped
。 - 使用 @ManagedProperty 似乎是理想的选择,除了我必须引入一个公共 setter 才能使其工作,这会损害封装性。
我可以使用类似的东西(在这个答案中提出):
@SuppressWarnings(“未选中”) 公共静态
T findBean(String beanName) { FacesContext 上下文 = FacesContext.getCurrentInstance(); return (T) context.getApplication().evaluateExpressionGet( 上下文, "#{" + beanName + "}", Object.class); } 我可以使用此方法来初始化
@PostConstruct
中的属性。这没有上述缺点,但看起来有点复杂。为什么我必须为框架应该提供的东西编写一个辅助方法?
我的问题是,我应该使用以上三种中的哪一种?另外,请随意纠正我在上面的描述中可能提出的任何误解,或者提出其他(更优雅的)方法来实现该目标。
The way I see it, there are three ways to get a reference to another bean:
- Using CDI, I can
@Inject
a named bean. This has the drawback that CDI-annotations don't mix well with faces-annotations, and thus I cannot use@ViewScoped
anymore. - Using
@ManagedProperty
seems to be ideal, apart from the fact that I have to introduce a public setter for that to work, which hurts encapsulation. I can use something like this (proposed in this answer):
@SuppressWarnings("unchecked") public static <T> T findBean(String beanName) { FacesContext context = FacesContext.getCurrentInstance(); return (T) context.getApplication().evaluateExpressionGet( context, "#{" + beanName + "}", Object.class); }
I can use this method to initialize the properties in my
@PostConstruct
. This has none of the drawbacks above, but seems a little bit complicated. Why would I have to write a helper-method for something the framework should provide?
My question is, which one of the three above should I use? Also, feel free to correct any misconceptions I may have stated in the description above, or to propose other (more elegant) methods to achieve that goal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你真的不能没有 @ViewScoed,并且你只想只使用 JSF 和 CDI - 那么第二个。不必担心外部依赖项的封装。即使在面部上下文之外,您仍然必须以某种方式设置另一个对象,因此需要设置器。
如果您想在图片中添加接缝,并且您无论如何都在使用 CDI,那么第一个。请参阅 jan groth 的回答。
If you really can't god without @ViewScoed, and you want to stay only with JSF and CDI - then the 2nd. Don't worry about encapsulation for external dependencies. Even outside a faces context you will still have to somehow set the other object, so a setter is due.
If you wish to add seam to the picture, and you are using CDI anyway, then the 1st. See the jan groth's answer.
绝对是第一,还有 Seam 3 Faces(此处)。只需将其放入您的类路径中,@Viewscoped 就可以在 CDI 和 JSF 之间完美桥接:-) 不用说,CDI 具有比 JSF 附带的更优越的依赖注入概念......
Definitely the 1st, together with Seam 3 Faces (here). Just put it in your classpath, and @Viewscoped is perfectly bridged between CDI and JSF :-) Needless to mention that CDI has the by far superior concept for dependency injection than what JSF ships with...