新聞中心
Spring中bean的作用域

創(chuàng)新互聯(lián)建站是一家專注于成都網(wǎng)站設計、成都網(wǎng)站建設與策劃設計,黃南州網(wǎng)站建設哪家好?創(chuàng)新互聯(lián)建站做網(wǎng)站,專注于網(wǎng)站建設十多年,網(wǎng)設計領域的專業(yè)建站公司;建站業(yè)務涵蓋:黃南州等地區(qū)。黃南州做網(wǎng)站價格咨詢:18982081108
Spring中bean的作用域用scope來表示。
scope的值有兩個:
singleton為單粒,即Spring IoC容器只會創(chuàng)建該bean的***一個實例,這也是默認的。該實例就會一直放在緩存里供大家使用。
prototype為原型,即每一次請求都會產(chǎn)生一個新的bean實例。
以實例說明
Bean
Java代碼
- package com.cos.bean110317;
- public class Bean1 {
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
applicationContext_5.xml
Xml代碼
- "1.0" encoding="UTF-8"?>
- "http://www.springframework.org/schema/beans"
- xmlns:amq="http://activemq.apache.org/schema/core" xmlns:jms="http://www.springframework.org/schema/jms"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd">
- "bean1" class="com.cos.bean110317.Bean1" scope="singleton">
- "name" value="zhangsan"/>
當scope不寫的時候默認為singleton
當scope為singleton的時候,輸出結(jié)果bean11 == bean12
當scope為prototype的時候,輸出結(jié)果bean11 != bean12
測試類
Java代碼
- package com.cos.bean110317;
- import org.springframework.beans.factory.BeanFactory;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class Test {
- public static void main(String[] args) {
- BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext_5.xml");
- Bean1 bean11 = (Bean1) factory.getBean("bean1");
- Bean1 bean12 = (Bean1) factory.getBean("bean1");
- if(bean11 == bean12){
- System.out.println("bean11 == bean12");
- }else{
- System.out.println("bean11 != bean12");
- }
- }
- }
【編輯推薦】
Struts VS Spring兩種MVC框架比較
Spring MVC框架的高級配置
Spring MVC框架的高級配置(上)
Spring MVC框架的高級配置(下)
設計REST風格的Java MVC框架:WebWind
分享文章:詳解Spring中bean的作用域
分享鏈接:http://fisionsoft.com.cn/article/dhsjgdh.html


咨詢
建站咨詢
