0
点赞
收藏
分享

微信扫一扫

计算机三级嵌入式知识点总结(一)

飞进科技 2024-11-03 阅读 7
javaspring

目录

15.1  引入

15.1.1  Orders类

15.1.2  bean-scope.xml

15.1.3  OrdersTest类

15.1.4  运行截图


15.1  引入

在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,各取值含义参加下表:

取值含义创建对象的时机
singleton(默认)在IOC容器中,这个bean的对象始终为单实例IOC容器初始化时
prototype这个bean在IOC容器中有多个实例获取bean时

如果是在WebApplicationContext环境下还会有另外几个作用域(但不常用):

取值含义
request在一个请求范围内有效
session在一个会话范围内有效

为了更加直观地展示singleton和prototype的Bean取值范围的不同,特给出如下代码

15.1.1  Orders类

package com.atguigu.spring6.iocxml.scope;

/**
* @package: com.atguigu.spring6.iocxml.scope
* @className: Orders
* @Description:
* @author: haozihua
* @date: 2024/10/18 21:06
*/

public class Orders {
}

15.1.2  bean-scope.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 http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="orders_prototype" class="com.atguigu.spring6.iocxml.scope.Orders" scope="prototype"></bean>
<bean id="orders_singleton" class="com.atguigu.spring6.iocxml.scope.Orders" scope="singleton"></bean>

</beans>

15.1.3  OrdersTest类

package com.atguigu.spring6.iocxml.scope;

import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* @package: com.atguigu.spring6.iocxml.scope
* @className: OrdersTest
* @Description:
* @author: haozihua
* @date: 2024/10/18 21:12
*/

public class OrdersTest {
@Test
public void OrderSingleton() {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean-scope.xml");
Orders ordersSingleton1 = context.getBean("orders_singleton", Orders.class);
Orders ordersSingleton2 = context.getBean("orders_singleton", Orders.class);
System.out.println(ordersSingleton1);
System.out.println(ordersSingleton2);
}
@Test
public void OrderPrototype() {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean-scope.xml");
Orders ordersPrototype1 = context.getBean("orders_prototype", Orders.class);
Orders ordersPrototype2 = context.getBean("orders_prototype", Orders.class);
System.out.println(ordersPrototype1);
System.out.println(ordersPrototype2);
}
}

15.1.4  运行截图

Singeleton结果

 Prototype结果

举报

相关推荐

0 条评论