使用CDI(上下文和依赖注入)支持bean而不是托管Bean

时间:2011-07-05 11:01:53

标签: java jsf java-ee jsf-2 cdi

我认为建议使用CDI bean作为支持bean而不是JSF托管bean。

所以我决定创建一个小例子来了解它的工作原理,对于 @RequestScopedBean

- 不使用 @ManagedBean(“beanName”),我使用 @Named(“beanName”)

- 而不是使用 javax.faces.bean.RequestScopped 我使用 javax.enterprise.context.RequestScoped;

演示程序非常简单,我有一个字段和一个提交按钮,当用户输入内容并刷新页面时,输入的值不再显示(请求持续时间是最后一次吗?)。我想我做的一切都很好,但我得到一个例外,说:

  

警告:StandardWrapperValve [面孔   Servlet]:PWC1406:Servlet.service()   for servlet Faces Servlet扔了   例外   javax.el.PropertyNotFoundException:   /index.xhtml @ 19,47   value =“#{cdiBean.passedValue}”:目标   无法访问,标识符'cdiBean'   解析为null

这就是我的程序的样子:

的index.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

<h:head>
        <title>RequestScope demo CDI(Component Dependency Injection)</title>
</h:head>

<h:body>

    <h:form>

    <h3>RequestScope demo CDI(Component Dependency Injection)</h3>

    <h:inputText value="#{cdiBean.passedValue}"/>
    <br/>
    <h:commandButton value="submit" action="index"/>

    </h:form>
</h:body>
</html>

DemoBB.java

package backingbeans;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named("cdiBean")//The Named anotation indicates that this is a CDI bean
@RequestScoped//If we use CDI beans the @RequestScoped annotation must come from: javax.enterprise.context.RequestScoped;
public class DemoBB {

    //This value will be saved on the session only until the server responds to the request
    private String passedValue;

    public String getPassedValue() {
        return passedValue;
    }

    public void setPassedValue(String passedValue) {
        this.passedValue = passedValue;
    }   
}

- 我的错误在哪儿?

- 使用这种方法有什么好处?我仍然不明白。

1 个答案:

答案 0 :(得分:3)

您的beans.xml是否有空web.xml?我认为必须在那里。

阅读第15.6节here。引用它:

  

CDI没有定义任何特殊内容   部署档案。你可以打包   JAR,EJB-JAR或WAR中的bean-any   应用程序中的部署位置   类路径。但是,存档必须   是一个“豆档案”。这意味着每一个   必须包含bean的存档   包含一个名为beans.xml的文件   类路径的META-INF目录或   Web根目录的WEB-INF目录(for   WAR档案)。该文件可能为空。   豆类部署在没有的档案中   有一个beans.xml文件将不会   可在应用程序中使用。

     

在可嵌入的EJB容器中,bean   可以部署在任何位置   可以部署哪些EJB。再次,   每个位置必须包含beans.xml   文件。