Search code examples
springscopecdi

Spring vs CDI scopes


Which are the exact differences between the scopes of Spring and CDI ? For example: Singleton (Spring) and ApplicationScoped (CDI)


Solution

  • TL;DR they are different, but you only mentioned some of the scopes of both worlds.

    Spring supports the following scopes:

    • Singleton
    • Prototype
    • Application (Web)
    • Session (Web)
    • Request (Web)

    Therefore the Singleton and Prototype scopes exist for any Spring application (managed by an ApplicationContext), even for a command line implementation. The scopes Application, Session and Request are introduced by a spring-web dependeny and managed by a WebAppicationContext in Spring.

    Spring typically creates a hierarchy of two DI contexts for a web application. The root context is bound to the main application and only offers Singleton and Prototype. The Web context, which uses the root context as a parent, is bound to the servlet context and offers all scopes. Only Application scope beans are available from servlet context as attributes (see also here).

    Jakarta EE offers the following build-in scopes:

    • Application
    • Session
    • Conversion
    • Request

    For Jakarta CDI the support of the build-in scopes is depending on the container management. Servlet containers typically support all of the above, others may only support the Application scope which in such a case behaves similar to the Spring Singleton scope.

    The scopes Application, Session and Request are similar in both worlds. There nothing like Conversation scope out of the box in Spring but you may implement custom scopes in both worlds and Conversation can be implemented similar to Session scope in Spring.