In Spring, beans are single-instance objects by default
public class Student {
}
<bean id="student" class="iocbean.byxml.example.Student">
</bean>
public class DemoTest {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("iocbean/byxml/example/bean.xml");
Student student1 = context.getBean("student", Student.class);
Student student2 = context.getBean("student", Student.class);
System.out.println(student1);
System.out.println(student2);
}
}
Result: (You can see that the address values of the two objects are the same)
iocbean.byxml.example.Student@5bd03f44
iocbean.byxml.example.Student@5bd03f44
Process finished with exit code 0
There are attributes (scope) in the bean tag of the spring configuration file to set single instance or multiple instances
- The default value, singleton, means a single-instance object
- prototype, which means it is a multi-instance object
<bean id="student" class="iocbean.byxml.example.Student" scope="prototype">
</bean>
Result: (You can see that the address values of the two objects are not the same)
iocbean.byxml.example.Student@470f1802
iocbean.byxml.example.Student@63021689
Process finished with exit code 0
The difference between singleton and prototype creating instance objects:
- When the scope value is set to singleton, a single instance object will be created when the spring configuration file is loaded
- When setting the scope value to prototype, instead of creating an object when loading the spring configuration file, create a multi-instance object when calling the getBean method