I have two ViewScoped CDI beans A and B and one JSF page. One bean (B) is injected into the other (A). Both are accessed directly from the JSF page. After some debugging I found that the instance of B injected into A is not the same as the instance of B accessed from the JSF page.
A:
package newpackage;
import java.io.Serializable;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
@Named
@ViewScoped
public class A implements Serializable {
@Inject
B b;
public int getValueB() {
int bb = b.getValueB();
return bb; // <- break here
}
}
and B:
package newpackage;
import java.io.Serializable;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
@Named
@ViewScoped
public class B implements Serializable {
Logger logger = Logger.getAnonymousLogger();
int randomNumber;
public B() {
logger.info("Constructor B called");
}
@PostConstruct
public void init() {
SecureRandom random = new SecureRandom();
randomNumber = random.nextInt();
logger.log(Level.INFO, "init B called: {0}", randomNumber);
}
public int getValueB() {
return randomNumber;
}
}
and the JSF page:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<h:body>
<h:outputText value="#{a.valueB}"/>
<h:outputText value="#{b.valueB}"/>
</h:body>
</html>
The instance of B injected into A (A.b) is not the same as the instance of B accessed directly from the JSF page (b.valueB). My expectation was they would be the same, since they're accessed at the same time on the same page. Is there an explanation for this? Was my expectation wrong?
Set a breakpoint at the line with the comment 'break here'. Now observe something peculiar: The value of the variable bb is a big random number; however, the value of A.b.randomNumber is 0. How can that be?