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

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