CDI Bean 方法在使用捆绑在 webapp 中的 myfaces 并在 Wildfly 上运行时未调用



我想将我的 JSF 应用程序从 ManagedBean 迁移到 CDI Beans。

首先,我做了一个简单的测试,看看CDI是否正常工作,但他们没有。 这是我的例子,使用 Wildfly 10 和 myfaces 2.2

bean.xml in .\WEB-INF

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>

XHTML 页面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>
test
</title>
</h:head>
<h:body>
<h:outputText value="#{CDITest.hello}"/>
<h:outputText value="test"/>
</h:body>
</html>

背豆

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;
@Named("CDITest")
@SessionScoped
public class CDITest implements Serializable{
public String getHello(){
return "Hello";
}
}

输出

测试

没有错误消息 (!(,也没有调用 CDITest.getHello(( 方法。我错过了什么?

这个问题更普遍。 在 JSF 2.3 中,JSF 通过 BeanManager#getELResolver 获取 CDI。在 JSF 2.3 之前的版本中,容器或 CDI impl 必须与 JSF 和 CDI 结合。

我认为您需要声明一个@FacesConfig注释类才能在 JSF 2.3 中激活 CDI

import javax.enterprise.context.ApplicationScoped;
import javax.faces.annotation.FacesConfig;
@FacesConfig
@ApplicationScoped
public class ConfigurationBean {
}

在 Wildfly 19.0.0 上升级到 myfaces-2.3.6 (jsf 2.3( 解决了这个问题。请注意,您需要一个 @Cristyan 建议的@FacesConfig类。

另请注意,使用 Mojarra 时问题没有发生,Bean 按预期工作(对于 Widlfly 10 和 Widlfly 19(。

相关内容

最新更新