When we add a bean in the spring container, if its scope property is not specified, it is singleton by default, that is, singleton.
For example, declare a bean first:
public class People { private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }Configure in applicationContext.xml file
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"> <bean id="people" >/bean></beans>
Then get it through the spring container:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); People p1=(People) context.getBean("people"); People p2=(People) context.getBean("people"); System.out.println(p1); System.out.println(p2); } }After running, you can see that the input contents of p1 and p2 are the same, indicating that the beans in spring are singleton.
If you don't want a singleton bean, you can change the scope property to prototype
<bean id="people" scope="prototype" ></bean>
In this way, the beans obtained through the spring container are not singletons.
By default, spring containers automatically create objects for all beans after startup. If you want to create them only when we get the bean, you can use the lazy-init property.
This property has three values: defalut, true, and false. The default is default. This value is the same as false. It creates a bean object when the spring container is started. When specified as true,
The object is created when we get the bean.
The above brief discussion on the initialization of beans in spring containers is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.