11

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.

0

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hey Nizet, I am little confuse. Can you give some example, where an application have multiple ServletContext.
Re-read. A web app has only one ServletContext. But it can have multiple Spring application contexts (often, one root context and one child web context per Spring dispatcher servlet)
multiple spring application contexts means, we can have multiple spring configuration files, right .. And we can define the same bean in multiple file right.. with scoped to "application". Is it what you are trying to say. Plz help me to understand. Thanks
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.