Search code examples
javaspringjakarta-eeejbjavabeans

Why Spring Bean is able to run in Tomcat Servlet Container but EJB not?


A lot of web resources say that Spring Bean is similar to EJB. The Spring bean also as EJB can define the logic via @Component, @Bean and @Service.

But EJBs cannot be run in servlet container like Tomcat.

What is key difference between EJB and Spring Beans?


Solution

  • It is not that much about what is the difference between Spring bean and EJB but how beforementioned are managed.

    Plain EJBeans or Spring beans do not have any special magic or functionality themselves. The functionality related is implemented in the environment that beans are run.

    When you run Spring application in Tomcat you actually run bunch of stuff from Spring framework that makes Spring beans work so not only the beans but lots of other code also that makes autowiring of services & components etc.. happen.

    However when you implement JavaEE with EJB all of the stuff you deploy consists only of your business code and beans not anything like Spring that has the managing logic also included.

    So EJB / JavaEE you need this managing stuff separately and this is why plain Tomcat is not enough for EJB. You need an J2EE container in which you run your EJBs for example - TomEE that is an extension having OpenEJB with Tomcat or see a list of Certified referencing runtimes (about in the middle of the Wikipage behind link).

    See also this and this related more or less.