1. 程式人生 > >spring創建Bean對象的控制

spring創建Bean對象的控制

style bean example main .get mage div 使用範圍 tex

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對象的控制