Spring学习笔记02_spring如何管理对象

IOC 中 bean 标签和管理对象细节

bean 标签

在这里插入图片描述

bean 的作用范围和生命周期

在这里插入图片描述

实例化 Bean 的三种方式

第一种方式:使用默认无参构造函数

<!--在默认情况下:
它会根据默认无参构造函数来创建类对象。如果 bean 中没有默认无参构造函数,将会创建失败。
--> 

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"/>

第二种方式:spring 管理静态工厂-使用静态工厂的方法创建对象

<!-- 此种方式是:
使用 StaticFactory 类中的静态方法 createAccountService 创建对象,并存入 spring 容器。
	id :			指定 bean 的 id,用于从容器中获取
	class :		指定静态工厂的全限定类名
	factory-method:属性:指定生产对象的静态方法
--> 

<bean id="accountService"
	 class="com.itheima.factory.StaticFactory"
	 factory-method="createAccountService">
</bean>

第三种方式:spring 管理实例工厂,使用实例工厂的方法创建对象

<!-- 此种方式是:
先把工厂的创建交给 spring 来管理。
然后在使用工厂的 bean 来调用里面的方法
factory-bean 属性:用于指定实例工厂 bean 的 id。
factory-method 属性:用于指定实例工厂中创建对象的方法。
--> 

<bean id="instancFactory" class="com.itheima.factory.InstanceFactory"></bean> 
<bean id="accountService"
	factory-bean="instancFactory"
	factory-method="createAccountService">
</bean>


Spring 管理示例

1、在类的根路径下(src下)创建bean.xml

xml文件名称自取,但不能含有中文

2、让 spring 管理资源,在配置文件中配置 service 和 dao

<!-- bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
	 id 属性:对象的唯一标识。
	 class 属性:指定要创建对象的全限定类名
-->

<!-- 配置 service --> 
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
<!-- 配置 dao --> 
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>

3、spring容器的获取和使用

public class Demo{
	/*使用 main 方法获取容器测试执行*/
	public static void main(String[] args) {
	//1.使用 ApplicationContext 接口,就是在获取 spring 容器
	//ClassPathXmlApplicationContext是从类的根路径下加载配置文件  推荐使用这种
	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
	//2.根据 bean 的 id 获取对象
	IAccountService aService = (IAccountService) ac.getBean("accountService");
	IAccountDao aDao = (IAccountDao) ac.getBean("accountDao");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值