Bean的实例化

Bean的实例化就是通过Spring容器帮我们创建对象实例。

Bean的实例化有三种方式:

1、构造器实例化:使用默认的构造方法实例化

在String容器的配置文件中的配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<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-4.3.xsd">


	<bean id="bean1" class="com.qiyue.instance.constructor.Bean1" />


</beans>

2、静态工厂方式实例化:

创建一个静态工厂类,在工厂中提供一个静态方法,通过静态方法实例化Bean。

在String容器的配置文件中的配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<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-4.3.xsd">

    <!-- class属性值为静态工厂的全限定名 -->
    <bean id="bean2" class="com.qiyue.instance.static_factory.MyBean2Factory" 
		   factory-method="createBean" />

    <!-- factory-method 属性值为静态工厂中的静态方法名称  -->
</beans>

3、实例工厂方式实例化:

创建实例工厂类,在工厂中提供实例Bean的方法,通过该方法实例化Bean。通过实例工厂实例化Bean的同时,实例工厂也会被实例化。

在String容器的配置文件中的配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<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-4.3.xsd">
    <!-- 配置实例工厂 -->
    <bean id="myBean3Factory" class="com.qiyue.instance.factory.MyBean3Factory" />

    <!-- 使用factory-bean属性指向配置的实例工厂,使用factory-method属性确定使用工厂中的哪个方法-->

	<bean id="bean3" factory-bean="myBean3Factory" factory-method="createBean" />
</beans>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值