Bean的实例化--静态工厂方式实例化

静态工厂实例化要求开发者创建一个静态工厂的方法来创建Bean的实例,其Bean配置中的class属性不再是Bean实例的实现类,而是静态工厂类,同时还需要使用factory-method属性来指定所创建的静态工厂方法。

一、在src目录下创建com.itheima.instance.static_factory包,并创建一个Bean类,不做任何处理,导包

二、在该包下创建一个MyBean2Factory类,并在该类中创建一个静态方法来返回Bean2 的实例

package com.itheima.instance.static_factory;

public class MyBean2Factory {
	//使用自己的工厂创建Bean2实例
	public static Bean2 createBean() {
		return new Bean2();
	}
}

三、在该包中创建Spring配置文件bean2.xml

<?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.xsd">
        
        <bean id="bean2"
         class="com.itheima.instance.static_factory.MyBean2Factory" 
         factory-method="createBean"/> 
 
</beans>

四、在该包下创建测试类

package com.itheima.instance.static_factory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InstanceTest2 {
	public static void main(String[] args) {
		//定义配置文件路径
		String xmlPath = "com/itheima/instance/static_factory/beans2.xml";
		//ApplicationContext在加载配置文件时,对Bean进行实例化
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		Bean2 bean = (Bean2) applicationContext.getBean("bean2");
		System.out.println(bean);
	}
}

运行结果:

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值