init method doesn't see new variable value made by contextInitialized metho

Hi all,

Maybe some of you will be able to help me with this little problem : i do not understand the behavior of the following example :
First, a string is initialised with the null value. Then the contextInitialized() method gives a “new value” to this string, ok.
Then, the init() method is executed, but the value of the string is “null” instead of “new value”.
Someone knows why ?

-1- testString from init() : null
-2- testString from contextInitialized() : New value !
-3- testString from init() : null


@Theme("testvaadin7theme")
@SuppressWarnings("serial")
public class Testvaadin7UI extends UI implements ServletContextListener{

	String testString = "null";
	
	@Override
	protected void init(VaadinRequest request) {
		System.out.println("testString from init() : "+testString);
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		testString = "New value !";
		System.out.println("testString from contextInitialized() : "+testString);
	}
}
+    Web.xml :
<listener>
      <listener-class>
           com.example.testvaadin7.Testvaadin7UI
      </listener-class>
</listener>

The contextInitialized() method initialises the whole application for all users.
The init() method initialises the session of a user.
These 2 methods are located in the same class, so if contextInitialized() updates a variable, this update must be seen by the ini() method.

The behavior is present in Vaadin 6, but not in Vaadin 7.
It is not the case with Vaadin 7, so i believe it is a bug.
Is it right ?

Eric

Hi. Actually, multiple instances of your class (
Testvaadin7UI
) are being created. First, one instance is created to act as a
ServletContextListener
. At this point, the
contextInitialized()
method is called so
testString
is initialized. But then, this current instance of your class is destroyed. Once a user request your webapp, another instance of your class (
Testvaadin7UI
) is created to act as a
UI
. But the
testString
variable is not initialized because it is a new instance of
Testvaadin7UI
.

If what you need is to store a value for every user, you should use the HTTP Sesion (
VaadinSession
). If all you need is to store an “application global” value, you can make
testString
static. Hope this helps.

I made this variable “static”.
Thank you Alejandro