Spring實戰(zhàn)之Bean的作用域singleton和prototype用法分析
本文實例講述了Spring實戰(zhàn)之Bean的作用域singleton和prototype用法。分享給大家供大家參考,具體如下:
一 配置
<?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文件創(chuàng)建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"));
}
}
四 測試結(jié)果
true
false
Thu Sep 19 20:56:59 CST 2019
Thu Sep 19 20:56:59 CST 2019
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Spring框架入門與進(jìn)階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
SpringBoot @PostMapping接收HTTP請求的流數(shù)據(jù)問題
這篇文章主要介紹了SpringBoot @PostMapping接收HTTP請求的流數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
IDEA插件之mybatisx插件使用教程(超詳細(xì)!)
MybatisX 是一款基于IDEA的快速開發(fā)插件,為效率而生,下面這篇文章主要給大家介紹了關(guān)于IDEA插件之mybatisx插件使用的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06
關(guān)于Controller 層返回值的公共包裝類的問題
本文給大家介紹Controller 層返回值的公共包裝類-避免每次都包裝一次返回-InitializingBean增強,本文通過實例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-09-09

