【小白日记】Attribute "scope" must be declared for element type "bean"问题解决方式 以及bean的理解 对Spring的初识和学习(4)...

本文介绍了Spring框架中Bean的作用域,包括singleton、prototype、request和session四种类型,并通过实例展示了如何配置不同作用域的Bean。

Spring中的bean(bean和scope引发的故事)

当正在探讨scope在bean中的关系 测试prototype关系时 源代码为

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id = "user" class="com.sky.spring.study03.User" scope = "prototype">
		<property name = "id" value = "1"></property>
		<property name = "name" value = "张三"></property>
		<property name = "age" value = "19"></property>
	</bean>
</beans>

发现scope报红

Attribute "scope" must be declared for element type "bean"

在这里插入图片描述
经过查阅发现是因为 该语法需要在bean2.0的环境下编写
将代码改为

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN 2.0/EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
	<bean id = "user" class="com.sky.spring.study03.User" scope = "prototype">
		<property name = "id" value = "1"></property>
		<property name = "name" value = "李四"></property>
		<property name = "age" value = "19"></property>
	</bean>
</beans>

解决问题

bean中scope的四种类型

  • singleton:单例,表示通过 Spring 容器获取的该对象是唯一的。
  • prototype:原型,表示通过 Spring 容器获取的对象是不同的。
  • reqeust:请求,表示在一次 HTTP 请求内有效。
  • session:会话,表示在一个用户会话内有效。
    其中,后两个只适用于 Web 项目,在大多数情况下,我们只会使用 singleton 和 prototype 两种 scope,并且 scope 的默认值是 singleton。

转载于:https://www.cnblogs.com/WeiHaoLee/p/10823340.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值