What is the default scope for a spring controller component?

Viewed 43

I'm diving into the spring bean scopes and application contexts topics and try to understand some concepts.

I understood that there is three main contexts. ApplicationContext (which is the context for a standalone app), WebApplicationContext for web based app (that extends ApplicationContext) and ServletContext (that is not Spring Related but a JEE thing, also related to web applications).

a WebApplicationContext contains all the Web related beans (controllers, ViewResolver etc ....), extends an ApplicationContext and reference a ServletContext

an ApplicationContext contains beans with singleton and prototype scope and a WebApplicationContext adds three scopes : request, session, websocket and application but application scoped beans are related to the ServletContext referenced in the WebApplicationContext.

What I'm not sure to understand is :

  • if controller components are contained in the WebApplicationContext, what is their default scope ? I thought it was singleton but in this case it makes no sense because the WebApplicationContext that contains those beans dies when the server is shut down

  • the documentation says that application scope is "somewhat similar to a Spring singleton bean but differs in two important ways: It is a singleton per ServletContext, not per Spring ApplicationContext (for which there may be several in any given web application), and it is actually exposed and therefore visible as a ServletContext attribute." Its clear, but I do not understand how we can have multiple servletContext for one applicationContext, I didn't find any use case for that. I've seen a usecase for multiple WebApplicationContext in the same app, like an app whith a REST API and a web front, but in this case, there is only one applicationContext and (I thought) only one servletContext shared by multiple WebApplicationContext.

1 Answers

I don't think there is a conflict between that Controller scope being a Singleton and the WebApplicationContext that contains those beans dies when the server is shut down, for the controller scope being a Singleton this means that the FactoryBeans creates one and only one istance of this controller and use it whenever it's called.

Related