Search code examples
javaspringtomcatservletsspring-ioc

Why servlet container not preferred over spring IOC container?


Servlet container implements web component contract of Java EE specification, specifying a runtime environment for web components that includes security, concurrency, lifecycle management, transaction, deployment, and other services.

Apache tomcat is one open source example.

Object satisfying the contract given by javax.servlet.ServletContext, is used per each web application


Spring IOC container also implement web component contract of Java EE specification.

Object satisfying the contract given by org.springframework.context.ApplicationContext, is used per each web application


Why Spring IOC container is preferred over servlet container?


Solution

  • There are many problematic statements in this question, I'll try to do my best to clarify few things by adding some "list" of facts that hopefully will help:

    1. Tomcat does not implement JEE specification, in fact, its famous only for implementing small (although important and widely-used) specification under the umbrella of JEE: servlets (and JSPs which a technically a servlet but in a more HTML like form).
    2. That's true that tomcat also follows a deployment model of WARs described in JEE, but in JEE there are much more types of archives that tomcat has nothing to do with. In addition, recent versions of tomcat allow "embedded mode", where you don't have to work with WARs at all.
    3. Spring, in a nutshell, is an IOC container, something that tomcat doesn't cover at all. I assume you know what is IOC, so I won't dig into IOC in this question.
    4. In addition to IOC, spring provides a fairly good integration with many different technologies (think about it as yet another thing that Spring can do). Now among these technologies, you can find Web Framework (called spring MVC), various templating engines (just like JSP), REST, working with database (Spring Data), Security model (Spring security) and many other things. All this makes spring a competitor of any implementation of JEE specification. Spring conceptually makes everything that JEE does (and arguably even more) but doesn't follow the standards established by JEE. Having said that, in modern versions, the difference becomes less and less significant, in many cases, Spring does honor interfaces and annotations offered by JEE, in addition to its own way to do stuff.

    5. So, now it's obvious that Spring and Tomcat don't really compete with each other. In fact, they can work together and its a really wide-spread tandem: One can use a spring framework to develop an application that will run on tomcat. Another successful model is to use spring boot that allows embedding the tomcat into the spring boot application and use it under the hood to server web (HTTP/Rest) requests.

    Hope this sheds some light and helps to understand the differences between Spring and Tomcat