com/spring-bean-scopes-singleton-vs-prototype/
When creating bean definitions you cannot only control various dependencies and
configurations, but also define the scope of the bean. These scopes are configured
via configuration which makes them very powerfull and flexible. You don’t need to
hard code them at Java Class level. There are multiple scopes. Singleton and
prototype are supported out of the box. The other scopes require a web-aware
ApplicationContext. Here is a list of the scopes available:
singleton (Default) Single bean definition for a single object instance per
container.
prototype Single bean definition for multiple instances.
request Single bean definition for a single HTTP request.
session Single bean definition for the HTTP session.
global-session Single bean definition for the global HTTP session. Typically
only valid when used in portlet context.
application Single bean definition for the entire application bound to the
lifecycle of a ServletContext
Request, session and application are only valid in the context of a web-aware
ApplicationContext
package com.memorynotfound.spring.core.scope;
We retrieve the singleton Coffee bean and assign a value. The subsequent
requests for the same bean will return the same instance of the bean.
package com.memorynotfound.spring.core.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Output
package com.memorynotfound.spring.core.scope;
package com.memorynotfound.spring.core.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
coffee = context.getBean(Coffee.class);
System.out.println("Coffee brand: " + coffee.getBrand());
}
}
Output
package com.memorynotfound.spring.core.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class Coffee {
<context:component-scan base-package="com.memorynotfound"/>
</beans>
References
Spring Bean Scope Doc
@Scope JavaDoc