您的位置:首页 > 编程语言 > Java开发

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

2017-03-12 20:24 676 查看
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接口】

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- IoC容器的配置,要创建的所有的对象都配置在这里 -->
<!-- <bean id="user" class="com.bie.po.User" scope="singleton"></bean> -->
<bean id="user" class="com.bie.po.User"></bean>
<!-- <bean id="user" class="com.bie.po.User" scope="prototype"></bean> -->
<bean id="user" class="com.bie.po.User" init-method=""></bean>
<bean id="user" class="com.bie.po.User" destroy-method=""></bean>
<bean id="user" class="com.bie.po.User" lazy-init="default"></bean>

</beans>


对于难啃的骨头,我想说只能一点点啃了~.-.~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: