【小白日記】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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM