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方法时返回该对象的引用。
发布了49 篇原创文章 · 获赞 1 · 访问量 930

猜你喜欢

转载自blog.csdn.net/qq_38783257/article/details/104270349