Spring之配置文件bean作用域的详细介绍

Spring的配置文件applicationContext.xml中bean作用域的详细介绍:

1:对象的创建:单例和多例
        scope="singleton",默认值,单例 适合于【service,dao,工具类】
        scope="prototype",多例适合于【Action对象】
2:什么时候创建对象?
      scope="singleton" 在启动的时候就已经创建了bean,且整个应用只有一个,在容器初始化之前
      scope="prototype" 在用到对象的时候才创建对象
3:是否延迟创建?(只对单例singleton有效,对多例无效):
       lazy-init="default" 默认是false,不延迟创建,即在启动的时候就创建对象
       lazy-init="true" 延迟初始化,在用到对象的时候才创建
4:初始化和销毁的方法:

  init-method="初始化方法名" 【对应对象的初始化方法,在对象创建之后执行】
      destroy-method="销毁的方法名" 【在调用容器对象的销毁方法的时候执行,容器必须使用实现类                                             ClassPathXmlApplicationContext,不能使用application接口】

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="
 7         http://www.springframework.org/schema/beans
 8         http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/context
10         http://www.springframework.org/schema/context/spring-context.xsd">
11      
12      
13      <!-- IoC容器的配置,要创建的所有的对象都配置在这里 -->
14      <!-- <bean id="user" class="com.bie.po.User" scope="singleton"></bean> -->
15      <bean id="user" class="com.bie.po.User"></bean>
16      <!-- <bean id="user" class="com.bie.po.User" scope="prototype"></bean> -->
17      <bean id="user" class="com.bie.po.User" init-method=""></bean>
18      <bean id="user" class="com.bie.po.User" destroy-method=""></bean>
19      <bean id="user" class="com.bie.po.User" lazy-init="default"></bean>
20      
21 </beans>     

对于难啃的骨头,我想说只能一点点啃了~.-.~

原文地址:https://www.cnblogs.com/biehongli/p/6539162.html