为什么不使用 BeanManager.getReference() 调用 @PostConstruct 方法来获取实例?

发布于 2025-01-01 06:40:37 字数 713 浏览 4 评论 0原文

我们目前正在从 JSF-ManagedBeans 迁移到 CDI。不幸的是,我们过去过度使用了 EL-Resolver,以获得对 JSF 管理的会话范围 bean 的静态访问。

由于 CDI 依赖注入并非在所有地方都可用,因此我重写了现有的静态查找以利用 BeanManager(使用扩展 BeanManagerAware 的 SEAM-Solder)。

Iterator<Bean<?>> iterator = beans.iterator();
Bean<T> bean = (Bean<T>) iterator.next(); // possible NPE, I know :)

CreationalContext<T> creationalContext = beanManager.createCreationalContext(bean);
T contextual = (T) beanManager.getReference(bean, type, creationalContext);

return contextual;

该代码运行并返回所需 bean 的容器管理实例。 但是:使用@PostConstruct注释的方法不会使用getReference()调用。也许你们知道该怎么做。无法通过谷歌搜索找到任何问题:-/

致以最诚挚的问候!

We are currently moving from JSF-ManagedBeans to CDI. Unfortunately we have made excessive use of the EL-Resolver in the past in order to gain static access to session scoped beans managed by JSF.

Since CDI dependency injection is not available everywhere I rewrote the existing static lookup to make use of the BeanManager (Using SEAM-Solder extending BeanManagerAware).

Iterator<Bean<?>> iterator = beans.iterator();
Bean<T> bean = (Bean<T>) iterator.next(); // possible NPE, I know :)

CreationalContext<T> creationalContext = beanManager.createCreationalContext(bean);
T contextual = (T) beanManager.getReference(bean, type, creationalContext);

return contextual;

The code works and returns a container managed instance of the desired bean. BUT: the methods annotated with @PostConstruct do not get called using getReference(). Perhaps you guys know how to do it. Couldn't find anything googling the issue :-/

Best regards!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巴黎夜雨 2025-01-08 06:40:37

您应该使用 Application#evaluateExpressionGet() 为此。不仅适用于 CDI bean,实际上也适用于您以前拥有的 JSF bean。

FacesContext context = FacesContext.getCurrentInstance();
Bean bean = (Bean) context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
// ...

然而,更干净的方法是使用 CDI 的 @注入或JSF的@ManagedProperty 相反。

另请参阅:

You should be using Application#evaluateExpressionGet() for this. Not only for CDI beans, but actually also for JSF beans you previously had.

FacesContext context = FacesContext.getCurrentInstance();
Bean bean = (Bean) context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
// ...

Much cleaner, however, is to just use CDI's @Inject or JSF's @ManagedProperty instead.

See also:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文