简体   繁体   中英

CDI lifecycle of bean, @Inject and params

The view and bean were working until I tried to fix non-standard names, and I've now broken the connection between the two. Oddly, the "back" button has the correct link, but content just doesn't show, nor log. Why doesn't Detail.getComments() execute?

I've been going through the weld docs and trying to better understand @Inject. There seems to be a lifecycle problem which I don't understand, either. If it's not lifecycle, then I cannot even speculate as to why Detail.getComments() never shows in the glassfish logs:

INFO: MessageBean.getModel..
INFO: SingletonNNTP.returning messages..
INFO: MessageBean.getModel..
INFO: SingletonNNTP.returning messages..
INFO: MessageBean.getModel..
INFO: SingletonNNTP.returning messages..
INFO: Detail..
INFO: Detail.getId..null
INFO: Detail.getId..SETTING DEFAULT ID
INFO: Detail.onLoad..2000
INFO: Detail.getId..2000
INFO: Detail.getId..2000
INFO: Detail.setId..2000
INFO: Detail.getId..2019
INFO: ..Detail.setId 2019
INFO: Detail.back..
INFO: Detail.getId..2019
INFO: ..Detail.back 2,018
INFO: Detail.getId..2019

The value 2000 is a default, which only happens when id==null, which it never should. It should pull in that attribute right away. So, I'm not sure whether that's a problem with the scope (I only just now found out that CDI doesn't support @SessionScoped), the lifecycle, or something else. Perhaps I need to use @Inject on that variable?

The view, detail.xhtml:

<?xml version='1.0' encoding='UTF-8' ?>
<!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:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
    <body>
        <f:metadata>
            <f:viewParam name="id" id="id" value="#{detail.id}" />
        </f:metadata>
        <ui:composition template="./complexTemplate.xhtml">
            <ui:define name="top">
                <h:link value="back" outcome="detail" includeViewParams="true">
                    <f:param name="id" value="#{detail.back}"/>
                </h:link>
            <ui:define name="content">
                <h:outputText value="#{detail.content}" rendered="false"/>
            </ui:define>
            <ui:define name="bottom">
                bottom
            </ui:define>
        </ui:composition>
    </body>
</html>

and the backing bean:

package net.bounceme.dur.nntp;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;
import javax.mail.Message;

@Named
@ConversationScoped
public class Detail  implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger.getLogger(Detail.class.getName());
    private static final Level level = Level.INFO;
    private String id = null;       //should never get default value in getter
    private Message message = null;
    private SingletonNNTP nntp = SingletonNNTP.INSTANCE;
    private String forward = null;  //id + 1
    private String back = null;     //id - 1
    private String content = null;  //message.content

    public Detail() {
        logger.log(level, "Detail..");
    }

    @PostConstruct
    private void onLoad() {
        logger.log(level, "Detail.onLoad..{0}", getId());
    }

    public Message getMessage() {
        logger.log(level, "Detail.getMessage..");
        return message;
    }

    public void setMessage(Message message) {
        logger.log(level, "Detail.setMessage..");
        this.message = message;
    }

    public String getId() {
        logger.log(level, "Detail.getId..{0}", id);
        if (id == null) {
            logger.log(level, "Detail.getId..SETTING DEFAULT ID");
            id = String.valueOf(2000);
        }
        return id;
    }

    public void setId(String id) throws Exception {
        logger.log(level, "Detail.setId..{0}", getId());
        this.id = id;
        logger.log(level, "..Detail.setId {0}", getId());
    }

    public String getForward() {
        logger.log(level, "Detail.forward..");
        int f = Integer.parseInt(getId());
        f = f + 1;
        logger.log(level, "..Detail.forward {0}", f);
        forward = String.valueOf(f);
        return forward;
    }

    public void setForward(String forward) {
        this.forward = forward;
    }

    public String getBack() {
        logger.log(level, "Detail.back..");
        int b = Integer.parseInt(getId());
        b = b - 1;
        logger.log(level, "..Detail.back {0}", b);
        back = String.valueOf(b);
        return back;
    }

    public void setBack(String back) {
        this.back = back;
    }

    public String getContent() throws Exception {
        logger.log(level, "Detail.getContent..{0}", getId());
        message = nntp.getMessage(Integer.parseInt(getId()));
        content = message.getContent().toString();
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

which never seems to have, according to the above logs, Detail.getContent() invoked, despite that being part of the view: <h:outputText value="#{detail.content}" rendered="false"/>

It's odd in that Detail.content() was getting invoked prior to my changing this class to better follow naming conventions. I'm going through some Weld and Oracle Java EE 6 docs, but don't at all mind being directed to a fine manual. The docs I find describing this are invariably using @ManagedBeans, however, which I am not. There seem many gotchas, as described in this answer by @Kawu.

Adding @Inject to the id field causes a deploy error:

init:
deps-module-jar:
deps-ear-jar:
deps-jar:
library-inclusion-in-archive:
library-inclusion-in-manifest:
compile:
compile-jsps:
In-place deployment at /home/thufir/NetBeansProjects/NNTPjsf/build/web
Initializing...
deploy?DEFAULT=/home/thufir/NetBeansProjects/NNTPjsf/build/web&name=NNTPjsf&contextroot=/NNTPjsf&force=true failed on GlassFish Server 3.1.2 
 Error occurred during deployment: Exception while loading the app : WELD-001408 Unsatisfied dependencies for type [String] with qualifiers [@Default] at injection point [[field] @Inject private net.bounceme.dur.nntp.Detail.id]. Please see server.log for more details.
/home/thufir/NetBeansProjects/NNTPjsf/nbproject/build-impl.xml:749: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 9 seconds)

Surely, injecting a String isn't the problem, perhaps it's a bug .

I understand your frustration, and I see that the problem is more your setup / understanding in general. But still, it's pretty hard to find any real questions to answer, maybe you can try to split your problems next time.

Here are some answers:

Why doesn't Detail.getComments() execute?

Hm, maybe because it's not in the bean? I guess that you are refrerring to detail.getContent instead?

which never seems to have, according to the above logs, Detail.getContent() invoked, despite that being part of the view:

Try rendered = true :-)

@PostConstruct
private void onLoad() {
    logger.log(level, "Detail.onLoad..{0}", getId());
}

You've put an awful lot of logic into the getter. Try debugging with the field, not with the getter...

The value 2000 is a default, which only happens when id==null, which it never should.

It looks like private String id = null; is a perfect explanation why id will be null.

Try to keep in mind that modern frameworks like JSF, CDI and Java EE do a lot of stuff behind the scenes, using reflection, proxies and interceptors. Don't rely on classical understanding of when (and how often) a constructor is called, for example.

Again, consider moving your initialisation logic away from the getter. @PostConstruct would be the place that the fathers of the Java EE-spec had chosen for it.

To be honest: Nothing looks extremely wrong, but your code is kind of messy, and extremely hard to understand and to follow.

Try removing all indirections like this one...

int b = Integer.parseInt(getId());

... and everything will look much better.

Oh, and is there a specific reason why you declare a fixed log-level for the whole class? Try something like this

private static final Logger LOG = Logger.getLogger(Some.class);
...
LOG.info("...");

Hope that gives you a start. Feel free to post further questions, preferably a bit shorter and with single, isolated aspects to answer.

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