-2

Both ServletContextEventHandler and static block have high startup priority. In usage, what is the difference? What should be put in the SC event handler and the static block?

Thanks Ming

Ming Leung
  • 385
  • 2
  • 13
  • The `static` code block will be executed when loading the class, so it will be executed first. It would be better if you post a real specific sample of what you're trying to achieve instead of just asking. Note that this can be easily proven with `System.out.println` on both cases. – Luiggi Mendoza Sep 05 '13 at 17:51

1 Answers1

3

I think you have a misunderstanding of the lifecycle of classes and objects.

A static block is executed when a class is loaded and this more or less depends on the ClassLoader your application is using. In a static context you only have access to other static components.

An object of type ServletContextEventHandler, by which I assume you mean ServletContextListener, is a hook that you can use to access your application's ServletContext when it is initialized and when it is destroyed.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • For more info about how class loaders work in java, refer to http://stackoverflow.com/q/11395074/1065197 and other links in the net like http://javarevisited.blogspot.com/2012/12/how-classloader-works-in-java.html and http://www.javaworld.com/jw-10-1996/jw-10-indepth.html – Luiggi Mendoza Sep 05 '13 at 17:57
  • And one more: http://javarevisited.blogspot.ca/2012/07/when-class-loading-initialization-java-example.html – Sotirios Delimanolis Sep 05 '13 at 17:58