I am developing a simple application on JSF having the following dependences
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-impl</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-api</artifactId>
<version>2.0.2</version>
</dependency>
and being a simple page with it backing bean.
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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<title></title>
</head>
<body >
<h:form>
<f:view >
<h:commandButton id="otxMainPanelTextBt" value="click"
action="#{otherController.doSome}"/>
</f:view>
</h:form>
</body>
</html>
Java code
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name = "otherController")
@ViewScoped
public class Other implements Serializable {
private static final long serialVersionUID = -6493758917750576706L;
public String doSome() {
System.out.println(this);
return "";
}
}
If I click on the commandButton many times according to toString source code it should write
class name+hashCode
but it writes something like the following
de.controller.Other@118ea91
de.controller.Other@1e8f930
de.controller.Other@1a38f3c
So, everytime we click there is a different hashcode for the viewscoped bean. Is this incorrect? I have tryed with session beans and this doesn't happen.
EDIT
I modified the class following @BalusC suggestion in the following way.
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name = "otherController")
@ViewScoped
public class Other implements Serializable {
private static final long serialVersionUID = -6493758917750576706L;
@PostConstruct
public void init()
{
System.out.println("Post Construction");
}
public Other()
{
System.out.println("Constructor");
}
public void doSome() {
System.out.println(this);
}
}
And I found this output after clicking many times.
Constructor
Post Construction
de.controller.Other@b748dd
de.controller.Other@1620dca
de.controller.Other@116358
de.controller.Other@73cb2d
de.controller.Other@1cc3ba0
So, the constructor and PostConstructor Methods are invoked only once, and in spite of this the object still has a different hashcode in every call. This is weird because the constructor with no parameter is supposed to be called on a managed bean instantiation, but it is not, so i still don't understand how can be the object created several times?