Spring中Bean的作用域有哪些,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
一 配置
<?xml version="1.0" encoding="GBK"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- 配置一個singleton Bean實例 --> <bean id="p1" class="org.crazyit.app.service.Person"/> <!-- 配置一個prototype Bean實例 --> <bean id="p2" class="org.crazyit.app.service.Person" scope="prototype"/> <bean id="date" class="java.util.Date"/></beans>
二 Bean
package org.crazyit.app.service;public class Person{ private int age;}
三 測試類
package lee;import org.springframework.context.*;import org.springframework.context.support.*;public class BeanTest{ public static void main(String[] args)throws Exception { // 以類加載路徑下的beans.xml文件創建Spring容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // ① // 判斷兩次請求singleton作用域的Bean實例是否相等 System.out.println(ctx.getBean("p1") == ctx.getBean("p1")); // 判斷兩次請求prototype作用域的Bean實例是否相等 System.out.println(ctx.getBean("p2") == ctx.getBean("p2")); System.out.println(ctx.getBean("date")); Thread.sleep(1000); System.out.println(ctx.getBean("date")); }}
四 測試結果
truefalseThu Sep 19 20:56:59 CST 2019Thu Sep 19 20:56:59 CST 2019
看完上述內容,你們掌握Spring中Bean的作用域有哪些的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。