In an application i'm working upon, there is a requirement like, few java classes needs to be instatntiated as the server starts up (for example getting the DB connection etc.), by reading an XML file. Can anybody please suggest the best way to achieve it (with some code if possible)?
Depends on the server. One of the WebSphere extensions (can't remember which) includes startup beans. WebLogic used to include the same. JBoss will load MBeans first - so you can implement it as one and you know it will be run before your application is deployed.
If however you want to do this in a platform independant way there are only two ways. One is a little complicated - since it relies on JMS, so we'll skip that. The other is to create a web app and implement a startup ContextListener which calls your startup code. When the web app is deployed the context listener will call your startup code.
In addition to having the servlet load on startup, another thing you can do is instantiate the need classes in the init method of the servlet. Remember that init is only fired when the servlet is first loaded (it's called by the container). It's also a good idea to clean things up in the destroy method.