首先需要在配置文件中定义bean,比如下面的文件:
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="studentbean" class="com.example.Student">
<property name="name" value="zzd"></property>
</bean>
<bean id="poemservicebean" class="cn.jiagoushi.poemgame.poemservicexml.PoemService">
</bean>
<bean id="checkanswerfactorybean" class="com.example.CheckAnswerServiceFactory">
</bean>
<bean id="duishicheckanswerbean" class="cn.jiagoushi.poemgame.domain.service.duishi.DuishiCheckAnswer">
<constructor-arg ref="poemservicebean"/>
</bean>
<bean id="feihualingcheckanswerbean" class="cn.jiagoushi.poemgame.domain.service.feihualing.FeihualingCheckAnswer">
<constructor-arg ref="poemservicebean"/>
</bean>
<bean id="jielongcheckanswerbean" class="cn.jiagoushi.poemgame.domain.service.jielong.JielongCheckAnswer">
<constructor-arg ref="poemservicebean"/>
</bean>
</beans>
每个bean有id和class,在constructor-arg中指出在构造函数中传入的bean。
在调用时,需要从配置文件中创建上下文: ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
在使用时,从上下文中获取bean:
ICheckAnswerServiceFactory factory=(ICheckAnswerServiceFactory)context.getBean("checkanswerfactorybean");
下面是使用这种方式创建的工厂类代码:
public class CheckAnswerServiceFactory implements ICheckAnswerServiceFactory {
@Override
public ICheckAnswerService GetService(GameType gameType) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
String servicetype = gameType.getMainType() + "checkanswerbean";
return (ICheckAnswerService) context.getBean(servicetype);
}
根据游戏的类型返回相应的服务,相关的服务在xml中注册,这里,根据传入参数可以获取具体的类型。






网友评论