• scope的范围


    (一)scope=“singleton”

    知识点:无论获取多少个bean,得到的总是一样的地址,singleton范围下只会创建一个bean实例

    1.Bean4.java

    package com.inspur.scope;
    
    public class Bean4 {
    
    }

    2.InstanceTest.java

    package com.inspur.scope;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.inspur.static_factory.Bean2;
    
    public class InstanceTest {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String xmlPath = "com/inspur/scope/beans4.xml";
            //2.ApplicationContext 在加载文件时,对bean实例化
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
            Bean4 bean4 = (Bean4) applicationContext.getBean("bean4");
            System.out.println(bean4);
            Bean4 bean5 = (Bean4) applicationContext.getBean("bean4");
            System.out.println(bean5);
    
        }
    
    }

    3.bean4.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        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.xsd">
           <bean id="bean4" class="com.inspur.scope.Bean4" scope="singleton"></bean>
    </beans>

    4.此时的运行结果是:

     5.如果将更改为prototype则获得两个不同的值。

    运行结果如下:

  • 相关阅读:
    春秋宋国
    MySQL查询性能优化七种武器之索引下推
    HbuliderX H5前端部署+Nginx+docker20220912
    春秋秦国
    春秋郑国
    docker安装 iotdb
    springboot集成Spring Batch 20220902
    跨境电商
    江西两大文化巨头:抚州有叫板江西的底气,吉安有叫板全国的底气
    CDH搭建教程
  • 原文地址:https://www.cnblogs.com/sunxiaoyan/p/9104757.html
Copyright © 2020-2023  润新知