SingletonScope And PrototypeScope : Constructor Injection « Spring « Java





SingletonScope And PrototypeScope

       
File: context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="singleMe" class="java.lang.String" scope="singleton">
        <constructor-arg type="java.lang.String" value="Singleton"/>
    </bean>

    <bean id="prototypeMe" class="java.lang.String" scope="prototype">
        <constructor-arg type="java.lang.String" value="Prototype"/>
    </bean>



</beans>


File: Main.java

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Main {
  private static void compare(final BeanFactory factory, final String beanName) {
    String b1 = (String)factory.getBean(beanName);
    String b2 = (String)factory.getBean(beanName);
    System.out.println("Bean b1=" + b1 + ", b2=" + b2);
    System.out.println("Same?  " + (b1 == b2));
    System.out.println("Equal? " + (b1.equals(b2)));
}

public static void main(String[] args) {
    BeanFactory factory = new XmlBeanFactory(
                        new ClassPathResource("context.xml"));
    compare(factory, "singleMe");
    compare(factory, "prototypeMe");
    compare(factory, "requestMe");
}
}




           
       










Spring-SingletonScopeAndPrototypeScope.zip( 2,599 k)

Related examples in the same category

1.Call Constructor
2.Constructor Confusion Demo
3.ConstructorCaller In ContextConfig
4.Constructor Argument And Local Reference