这篇文章给大家介绍Spring中调用实例工厂方法创建Bean,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
一 配置
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 配置工厂Bean,该Bean负责产生其他Bean实例 -->
<bean id="personFactory" class="org.crazyit.app.factory.PersonFactory"/>
<!-- 下面配置驱动Spring调用personFactory Bean的getPerson()方法来创建Bean
该bean元素包含的constructor-arg元素用于为工厂方法指定参数,
因此这段配置会驱动Spring以反射方式来执行如下代码:
PersonFactory pf = container.get("personFactory"); // container代表Spring容器
chinese = pf.getPerson("chin"); -->
<bean id="chinese" factory-bean="personFactory"
factory-method="getPerson">
<!-- 配置实例工厂方法的参数 -->
<constructor-arg value="chin"/>
</bean>
<!-- 下面配置会驱动Spring以反射方式来执行如下代码:
PersonFactory pf = container.get("personFactory"); // container代表Spring容器
american = pf.getPerson("ame"); -->
<bean id="american" factory-bean="personFactory"
factory-method="getPerson">
<constructor-arg value="ame"/>
</bean>
</beans>
二 接口
Person
package org.crazyit.app.service;
public interface Person
{
// 定义一个打招呼的方法
public String sayHello(String name);
// 定义一个告别的方法
public String sayGoodBye(String name);
}
三 实现类
American
public class American implements Person
{
// 实现Person接口必须实现如下两个方法
public String sayHello(String name)
{
return name + ",Hello!";
}
public String sayGoodBye(String name)
{
return name + ",Good Bye!";
}
}
Chinese
package org.crazyit.app.service.impl;
import org.crazyit.app.service.*;
public class Chinese implements Person
{
// 实现Person接口必须实现如下两个方法
public String sayHello(String name)
{
return name + ",您好";
}
public String sayGoodBye(String name)
{
return name + ",下次再见";
}
}
四 工厂类
package org.crazyit.app.factory;
import org.crazyit.app.service.*;
import org.crazyit.app.service.impl.*;
public class PersonFactory
{
// 获得Person实例的实例工厂方法
// ethnic参数决定返回哪个Person实现类的实例
public Person getPerson(String ethnic)
{
if (ethnic.equalsIgnoreCase("chin"))
{
return new Chinese();
}
else
{
return new American();
}
}
}
五 测试类
package lee;
import org.springframework.context.*;
import org.springframework.context.support.*;
import org.crazyit.app.service.*;
public class SpringTest
{
public static void main(String[] args)
{
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
Person p1 = ctx.getBean("chinese"
, Person.class);
System.out.println(p1.sayHello("Mary"));
System.out.println(p1.sayGoodBye("Mary"));
Person p2 = ctx.getBean("american"
, Person.class);
System.out.println(p2.sayHello("Jack"));
System.out.println(p2.sayGoodBye("Jack"));
}
}
六 测试
Mary,您好
Mary,下次再见
Jack,Hello!
Jack,Good Bye!
关于Spring中调用实例工厂方法创建Bean就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。