zoukankan      html  css  js  c++  java
  • 【sping揭秘】3、Spring容器中bean默认是保持一个实例

    Spring容器中bean默认是保持一个实例

    这里做一个测试,基础代码

    package cn.cutter.start.provider;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.stereotype.Component;
    
    @Component(value="FXNewsProvider")
    public class FXNewsProvider {
        //做个变量用来监控2个对象bean之间的值是否一致,来确认是否是一个对象
        private int testSpring;
        
        public FXNewsProvider() {
            System.out.println("hello IOC");
            ++testSpring;
        } 
        
        
        public static void main(String[] args) {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("配置文件路径");
            FXNewsProvider fxNewsProvider = (FXNewsProvider) ctx.getBean("fXNewsProvider");
        }
    
    
        public int getTestSpring() {
            return testSpring;
        }
    
    
        public void setTestSpring(int testSpring) {
            this.testSpring = testSpring;
        }
        
        
    }

    测试案例:

    @Test
        public void test2() {
            
            //测试spring的IOC容器中,默认是保持在IOC容器中只有一个实例
            ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:application-bean.xml");
            FXNewsProvider fxNewsProvider = (FXNewsProvider) ctx.getBean("FXNewsProvider");
            
            System.out.println("第一次获取值:" + fxNewsProvider.getTestSpring());
            
            FXNewsProvider fxNewsProvider2 = (FXNewsProvider) ctx.getBean("FXNewsProvider");
            System.out.println("第二次获取值:" + fxNewsProvider2.getTestSpring());
            
            fxNewsProvider2.setTestSpring(998);
            
            if(fxNewsProvider2 == fxNewsProvider) {
                System.out.println("两次对象一样,值为:" + fxNewsProvider.getTestSpring());
            } else {
                System.out.println(fxNewsProvider.getTestSpring());
                System.out.println(fxNewsProvider2.getTestSpring());
            }
            
        }

    最后我们看一下测试结果

    果然如书中所料。。。

  • 相关阅读:
    使用turtle库绘制一个叠加等边三角形
    使用turtle库绘制图形
    tar命令常用参数讲解
    elasticsearch 中geo point地理位置数据类型
    count(*)和count(1)的sql性能分析
    别再if/else走天下了
    正则表达式 匹配0次1次或者无限次
    linux shell 字符串操作(长度,查找,替换)
    linux expect工具使用
    mongodb分片balance
  • 原文地址:https://www.cnblogs.com/cutter-point/p/8597702.html
Copyright © 2011-2022 走看看