简体   繁体   中英

CDI Beans not retaining values

I'm working on a large JSF project but have noticed that none of my session beans are retaining their values. In order to try and find my error I created a test project with a simple injection, however I am still finding the session scoped bean is not retaining its values.

I have searched through stackoverflow.com (and spent several hours on Google) for an answer but cannot find one. I would be very grateful for any help.

I am using JSF 2.2, Netbeans 7.3.1 & Glassfish Server 4.0

The code for my simple test project is below.

beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

index.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:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Title</title>
    </h:head>
    <h:body>
        <h:form>
            <h:inputText value="#{bean1.title}" />
            <h:commandButton action="#{bean2.test()}" />
        </h:form>
    </h:body>
</html>

Bean1.java

package beans;

import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;


@Named(value = "bean1")
@SessionScoped
public class Bean1 implements Serializable {

    public Bean1() {
    }

    private String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Bean2.java

package beans;

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

@Named(value = "bean2")
@RequestScoped
public class Bean2 {

    public Bean2() {
    }

    @Inject
    Bean1 b1;

    public String test()
    {
        System.out.println(b1.getTitle());

        return null;
    }   
}

If I had to guess, your CDI 1.0 beans.xml is causing confusion in the app server. Try upgrading to a CDI 1.1 beans.xml

<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>

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