一、作用域
Spring中bean有6种作用域(singleton、prototype、request、session、application、websocket),该篇文章仅讲前两种。
项目结构:
两个实体类
public class Customer {
}
public class User {
}
pojos.xml配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 默认创建bean对象就是单例的(默认这一句就是加上的:scope="singleton") -->
<bean id="user" class="com.shengjava.pojo.User" scope="singleton"></bean>
<!-- 修改为prototype,此时每次创建的对象都是一个新对象 -->
<bean id="customer" class="com.shengjava.pojo.Customer" scope="prototype"></bean>
</beans>
测试:
public class UserTest {
@Test
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("pojos.xml");
User user1 = context.getBean("user", User.class);
User user2 = context.getBean("user", User.class);
Customer customer1 = context.getBean("customer", Customer.class);
Customer customer2 = context.getBean("customer", Customer.class);
System.out.println(user1 == user2);
System.out.println(customer1 == customer2);
}
}
输出:
因为user1和user2作用域都是singleton单例的,他俩是一个对象,所以输出true。
而customer1和customer2作用域为prototype,每次获取都是以恶个新对象,并不相等,所以输出false。
true
false
参考官方文档:
1.5. Bean Scopes
相关
我的该分类的其他相关文章,请点击:【Spring + Spring MVC + MyBatis】文章目录