Spring(四)之bean创建顺序与单多实例

改变创建顺序

<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="person1" class="helloWorld.Person"></bean>
    <bean id="car1" class="helloWorld.Car"></bean>
    <bean id="book1" class="helloWorld.Book"></bean>
</beans>

创建顺序是按照顺序创建,如果加了depend-on属性

<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="person1" class="helloWorld.Person" depend-on="car1,book1"></bean>
    <bean id="car1" class="helloWorld.Car"></bean>
    <bean id="book1" class="helloWorld.Book"></bean>
</beans>

那么此时顺序是car,book,person

改变默认单实例

bean的创建默认是单实例的,如果要修改多实例怎么办?

<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="car1" class="helloWorld.Car" scope="prototype"></bean>
</beans>

这就需要用到scope属性。

  • prototype:代表多实例,每次调用getBean方法时都会创建一个新的对象。
  • singleton:代表单实例,在容器创建时就创建一个对象每次调用getBean方法时返回该对象的引用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值