Detailed scope effect

First create a UserInfo class, and then add the class in the application.xml:

package club.affengkuang.vo;

public class UserInfo {
	
	public UserInfo() {
		System.out.println("构造方法");
	}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="userInfo" class="club.affengkuang.vo.UserInfo" lazy-init="true"></bean>
</beans>

Then we create a test class IOC container in a UserInfo class and obtain two objects, and their values ​​are printed, you will find an object twice acquired the same object:

package club.affengkuang.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
		Object object = applicationContext.getBean("userInfo");
		System.out.println(object);
		object = applicationContext.getBean("userInfo");
		System.out.println(object);
		applicationContext.close();
	}
}

This is the scope in the role, scope has four values:

prototype: every time you can create a new object in the container
singleton: container can only create an object
session: the same session object is created in only one
request: to create only one object in the same request

Wherein the latter two are used in Javaweb project, and the default value of scope is singleton, so IOC example acquires the two objects in the container to obtain the same object.

Then we will modify the scope of value for the prototype and then execute the test class in the code, it creates two different objects: the

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

	<bean id="userInfo" class="club.affengkuang.vo.UserInfo" lazy-init="true" scope="prototype"></bean>
</beans>

Published 99 original articles · won praise 93 · views 5208

Guess you like

Origin blog.csdn.net/DangerousMc/article/details/104450460