15. Bean Scopes

Bean Scopes
                At the time of bean Object creation, we can pass the scope to the bean.
                Container will create the Object by considering the Scope
                We have 5 types of bean Scopes
1.      Singleton
2.      Prototype
3.      Request
4.      Session
5.      Global-session
Example:  see here SimpleBean.java, SimpleMain.java is common for all. Only simple.xml is vary.

// SimpleBean.java
                package bean;

public class SimpleaBean {
       private String msg;
       public void setMsg(String msg) {
              this.msg = msg;
       }
       public String getMsg() {
              System.out.println(msg);
              return msg;
       }
}

// SimpleMain.java
package main;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.SimpleaBean;

public class SimpleMain {
public static void main(String[] args) {
       BeanFactory factory = new ClassPathXmlApplicationContext("res/simple.xml");
       SimpleaBean b1 = (SimpleaBean) factory.getBean("ob");
       b1.setMsg("Hello.....");
       b1.getMsg();
      
       SimpleaBean b2 = (SimpleaBean) factory.getBean("ob");
       b2.getMsg();
}
}

1)      Singleton                    : Spring to return the same bean instance each time one is needed (default).
Example: simple.xml
<beans>
              <bean id="ob" class="bean.SimpleaBean" scope="singleton"/>           
    
</beans>
Output
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Hello.....
Hello.....

2)      Prototype                    : Spring to produce a new bean instance each time the new Object is needed.
Example: simple.xml
<beans>
       <bean id="ob" class="bean.SimpleaBean" scope="prototype"/>
</beans>

Output
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Hello.....
Null

3)      Request                        : This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
4)      Session                         : This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
5)      Global-session         : This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

Post a Comment

Thank You

Previous Post Next Post