Home >Java >javaTutorial >A brief discussion on the initialization of beans in spring containers
When we add a bean in the spring container, if its scope attribute is not specified, the default is singleton, which is a 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 the 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" class="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 Beans in spring are singletons.
If you don’t want a singleton bean, you can change the scope attribute to prototype
<bean id="people" class="People" scope="prototype" ></bean>
In this way, the bean obtained through the spring container is not a singleton.
The spring container automatically creates objects for all beans after startup by default. If you want to create them when we get the beans, you can use the lazy-init attribute
This attribute has three Value defalut, true, false. The default is default. This value is the same as false. The bean object is created when the spring container starts. When true is specified, the object is created only when we obtain the bean.
The above article briefly discusses the initialization of beans in the spring container. This is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.
For more articles related to the initialization of beans in spring containers, please pay attention to the PHP Chinese website!