Ishant Gaurav
Ishant Gaurav

Reputation: 1203

How many spring beans will be created in following Case

According to me only one bean should be created since i have given the scope as singleton but output is saying different thing. Can anyone please ellaborate the following to me please,

HelloWorld.java

public class HelloWorld {
    private String message;

    public HelloWorld(String message) {
        System.out.println(message+ "bean created");
        this.message=message;
    }

    public void getMessage() {
        System.out.println("Your Message : " + message);
   }
}

Main.java

public class Main {
    public  static void main(String args[]) {

        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
        obj.getMessage();

        HelloWorld obj2 = (HelloWorld) context.getBean("helloWorld2");
        obj2.getMessage();
        obj.getMessage();

        System.out.println(obj.hashCode());
        System.out.println(obj.hashCode());
    }
}

beans.xml

<bean id = "helloWorld" class = "HelloWorld" scope="singleton">
    <!--<property name = "message" value = "Hello World!"/>-->
    <constructor-arg value="HelloWorld1"/>
</bean>

<bean id = "helloWorld2" class = "HelloWorld" scope="singleton">
    <!--<property name = "message" value = "Hello World2!"/>-->
    <constructor-arg value="HelloWorld2"/>
</bean>

Output:

HelloWorld1bean created
HelloWorld2bean created
Your Message : HelloWorld1
Your Message : HelloWorld2
Your Message : HelloWorld1
935148943
935148943

Upvotes: 0

Views: 1187

Answers (2)

Bhushan Uniyal
Bhushan Uniyal

Reputation: 5703

No here 2 singleton beans will create becaue you are creating 2 different beans for HelloWorld

<bean id = "helloWorld" class = "HelloWorld" scope="singleton">
    <!--<property name = "message" value = "Hello World!"/>-->
    <constructor-arg value="HelloWorld1"/>
</bean>

<bean id = "helloWorld2" class = "HelloWorld" scope="singleton">
    <!--<property name = "message" value = "Hello World2!"/>-->
    <constructor-arg value="HelloWorld2"/>
</bean>

Spring container create 1 object per definition, If we define bean N times than N singleton object of the class will be created

Upvotes: 0

Shadi Al Barhouch
Shadi Al Barhouch

Reputation: 117

Definitely 2 Try to print obj2.hashcode. Not obj hashcode

Upvotes: 1

Related Questions