Tutorials Spring Spring Bean Scope Using XML Configuration and @Scope Annotation

Spring Bean Scope Using XML Configuration and @Scope Annotation

When you declare a POJO instance or bean in the configuration file, you are actually defining a template for bean creation, not an actual bean instance. The actual bean instance is created when the getBean() method is called. While bean is instantiated by the Spring IoC, the framework decides the scope of the instance.

Following are the different bean instance scopes supported in Spring.

  • singleton – Creates at most one bean instance per Spring IoC container
  • prototype – Creates a new instance each requested
  • request – Creates a single bean instance per HTTP request;
  • session – Creates a single bean instance per HTTP session;
  • global session- Creates a single bean instance per global HTTP session

You can set the bean scope using the element scope attribute. The default scope fro bean is set to Singleton. This means that only one instance of bean can be created in the IoC container and the same instance can be shared across.

The following code snippet shows how to define the bean scope using XML configuration.


      
      

You can also specifying bean scope from Java code using @Scope annotation as follows:

@Configuration
public class MyBeanConfig {
    @Bean
    @Scope(value = BeanDefinition.SCOPE_SINGLETON)
    public Crayon crayonToy() {
        return new Crayon("Yellow crayon", 50);

    }
}
Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post

Spring Bean Configuration using @Configuration and @Bean Annotations

Next Post

How to Initialize Bean by Reading Data from .properties File in Spring

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x