简体   繁体   中英

CDI Produces Method - Injection

I'm trying to learn the use of @Produces methods in CDI. I have made really simple web-app to test it out. What I'm trying to do is basically is upon submission of the form pass the value of one bean (Controller) to the other (Cont).

The problem is though that the str value never gets "injected". Obviously there are other ways to do this (inject the entire controller) but I'm trying to learn this specific way.

.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>
</h:head>

<h:body>
    <h:form>

        <h:outputText value="Input: " />
        <h:inputText value="#{str}" />
        <br />
        <br />

        <h:outputText value="#{cont.str}" />
        <br />
        <br />

        <h:commandButton value="Submit">
        </h:commandButton>
    </h:form>
</h:body>

Controller.java

@Named
@SessionScoped
public class Controller implements Serializable {


    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Produces
    @Named("str")
    private String str;


    public String getStr() {
        return str;
    }


    public void setStr(String str) {
        this.str = str;
    }
}

Cont.java

@Named
@SessionScoped
public class Cont implements Serializable {



    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    @Inject
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }


}

Change your h:inputText to use #{cont.str}

The use of a producer here is awkward. @Named is always evaluated, it's best to use a wrapper object to handle it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM