gpt4 book ai didi

jsf-2 - 无法在 EL/Facelet 中找到具有默认名称的 @Named CDI bean

转载 作者:行者123 更新时间:2023-12-05 00:28:07 25 4
gpt4 key购买 nike

jee6 tutorial我可以阅读以下内容:

The @Named qualifier allows you to access the bean by using the bean name, with the first letter in lowercase. For example, a Facelets page would refer to the bean as printer.

You can specify an argument to the @Named qualifier to use a nondefault name:



但是,当我尝试在不添加参数的情况下使用 @Named 时,找不到我的 bean,并且出现如下异常。
@Named
@ViewScoped
public class MTestBean {
...
}

异常(exception);
javax.servlet.ServletException: /MyPage.xhtml @15,65 listener="#{mTestBean.init}": Target Unreachable, identifier 'mTestBean' resolved to null

但如果我使用
@Named("mTestBean")

一切正常。这是预期的行为吗?有没有办法可以列出 EL 中可用的 bean,也许我假设了错误的默认名称?

最佳答案

您实际上必须使用 #{MTestBean.xxx} 来引用 bean。有趣的是,NetBeans 对默认名称做出了相同的假设,并将使用 #{mTestBean.xxx} 自动完成。正如 BalusC 所指出的,这种命名行为确实遵循 JavaBeans 规范。从第 8.8 节 -

...to support the occasional use of all upper-case names, we check if the first two characters of the name are both upper case and if so leave it alone. So for example, “FooBah” becomes “fooBah” “Z” becomes “z” “URL” becomes “URL” We provide a method Introspector.decapitalize which implements this conversion rule.



就用 CDI 列出可用的 bean 而言,最好的选择是 javax.enterprise.inject.spi.BeanManager。看到这个 link

编辑:这是一个从链接稍微修改的版本,以显示 EL 名称,而不仅仅是类。
public void listAllBeans() throws NamingException{
//Get the BeanManager
InitialContext initialContext = new InitialContext();
BeanManager bm = (BeanManager) initialContext.lookup("java:comp/BeanManager");

//List all CDI Managed Beans and their EL-accessible name
Set<Bean<?>> beans = bm.getBeans(Object.class,new AnnotationLiteral<Any>() {});
for (Bean<?> bean : beans) {
System.out.println(bean.getBeanClass().getName() + " / bean name = " + bean.getName());
}
}

我们的测试 bean 的输出 -

com.xxx.jsf.beans.MTestBean / bean name = MTestBean

关于jsf-2 - 无法在 EL/Facelet 中找到具有默认名称的 @Named CDI bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com