I was trying to understand how the Web Services work and I came across this tutorial
Now, I've seen spring being used in enterprise applications and always wondered where the main method was and how everything worked? And whenever I would go to spring tutorial they'll start with beanFactory and Contexts and what not, all in a main java method and from there just keep getting beans as required. This is totally different from what I see in the applications.
Can someone tell me how exactly does spring work in this case. What is the sequence of calls. I guess there will be some hidden main method somewhere but I am not sure of that.
Normally if I were to run a simple java project from command line, I'd do java mainClass
. Now how would it happen in this case.
Thanks
Web applications are not standalone application, they run on some applications what we call servletContainer in java context so there is no
main method or java process(os)
for any web application. They are just deployed on those containers that have main method and java process in OS runtime.Web applications don't have a main; the 'program' that is running is actually the web container (Apache Tomcat, Glassfish, JBoss, Weblogic, whatever) and that program will service the web application(s) you deploy into it. You might want to read the JEE tutorial to learn and understand what a Java web environment is.
https://docs.oracle.com/javaee/7/tutorial/
You don't see any explicit
main
method just because it is a Web project. This project is built into a web application archive (WAR) file which is deployed into a web server / servlet container, e.g. Tomcat in this tutorial.Web applications does not have to contain
main
methods. This is because you don't need to explicitly start any Java process from within your webapp. Somewhere in its depths, Tomcat calls amain
method of the code it has been built from. This happens at server startup time.Then, it will bind your code to incoming HTTP calls, but it will not start new processes for that. It will rather start new threads.
There is still a main method, it's just not written by the developer of the application but by the developer of the container.
You can still see the main method being called by using the debugger like this:
This is an example with jetty:
To see this we need to put the breakpoint in an initialization method so that we get the main thread of the application.
Putting the breakpoint in the processing of a request instead of an initialization method would show Thread.run() at the bottom of the stack trace and not main().
Thread.run() is the equivalent of the main method for threads other than the main thread.
So the main method still exists, it's just being handled at the level of the container.