7
votes

Could anyone explain the difference between these two Spring bean scopes? I'm familiar with the Singleton pattern.

Would this be the only difference? You can have a list of beans in the Spring container using application scope.

Also, are you able to run multiple web servers in one Spring container? If yes, that would be a reason to use the application scope over the singleton scope since otherwise the bean would get shared over the two servers.

2

2 Answers

5
votes

The documentation explains it:

This is somewhat similar to a Spring singleton bean but differs in two important ways: It is a singleton per ServletContext, not per Spring 'ApplicationContext' (or which there may be several in any given web application), and it is actually exposed and therefore visible as a ServletContext attribute

2
votes

In application scope, the container creates one instance per web application runtime. The application scope is almost similar to singleton scope. So, the difference is

Application scoped bean is singleton per ServletContext however singleton scoped bean is singleton per ApplicationContext. It means that there can be multiple application contexts for single application.

SINGLETON SCOPED BEAN

//load the spring configuration file
ClassPathXmlApplicationContext context =
        new ClassPathXmlApplicationContext("context.xml");

// retrieve bean from spring container
MyBean myBean = context.getBean("myBean", MyBean.class);
MyBean myBean2 = context.getBean("myBean", MyBean.class);

// myBean == myBean2 - output is true.