码迷,mamicode.com
首页 > 编程语言 > 详细

spring创建Bean对象的控制

时间:2018-08-01 17:16:09      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:oid   返回   自定义   默认   支持   contex   范围   模式   alt   

1、spring创建Bean对象的控制

       a、控制对象创建方式(使用范围),在<bean>元素中使用scope属性控制,scope可以支持singleton或prototype,默认值是singleton

              <bean scope= "singleton"> 该组件在spring容器里只有一个bean对象。每次取出的bean都是同一个bean,相当于单例模式

              <bean scope = "prototype">该组件每次使用getBean("")都会返回一个新的对象

例如我们自定义了一个ExampleBean类:

public class ExampleBean {
   public void execute() {
       System.out.println("调用了execute方法");
   }
}

在applicationContext.xml中进行配置,默认使用scope="singleton"

<!-- 创建一个ExampleBean对象 -->
    <bean id ="example" class="com.zlc.test.ExampleBean"></bean>

我们测试一下每次取出的bean是否为同一个bean:

public static void main(String[] args) {
        String conf = "applicationContext.xml";
        //创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext(conf); 
        //得到Example对象
        ExampleBean e1 = ac.getBean("example",ExampleBean.class);
        ExampleBean e2 = ac.getBean("example",ExampleBean.class);
        System.out.println(e1 == e2);    
    }

运行结果:

技术分享图片

由此可见:每次我们从容器中取出的对象都是同一个对象

spring创建Bean对象的控制

标签:oid   返回   自定义   默认   支持   contex   范围   模式   alt   

原文地址:https://www.cnblogs.com/zlingchao/p/9402310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!