SpringIOC容器-xml配置bean-工厂方式配置Bean
Posted linglongfang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringIOC容器-xml配置bean-工厂方式配置Bean相关的知识,希望对你有一定的参考价值。
一、实验使用实体类
1.静态工厂配置Bean
静态工厂类 StaticFactory
package com.llf.bean.factory; import com.llf.bean.Car; import java.util.HashMap; import java.util.Map; /** * @author linglongfang */ public class StaticFactory { private static Map<String,Car> carFactory = null; static { carFactory = new HashMap<>(); carFactory.put("长安",new Car("长安",120,80000)); carFactory.put("解放",new Car("解放",150,500000)); } /** * 生产指定的Car * @return */ public static Car getCar(String carName){ return carFactory.get(carName); } }
xml中配置
class:静态工厂的类,factory-method:生产bean的静态方法,如果factory-method方法有参数,那么用<constructor-arg>标签来注入参数
<bean id="car" class="com.llf.bean.factory.StaticFactory" factory-method="getCar"> <constructor-arg name="carName" value="解放"></constructor-arg> </bean>
2.实例工厂配置Bean
实例工厂类 Factory
package com.llf.bean.factory; import com.llf.bean.Car; import java.util.HashMap; import java.util.Map; /** * @author linglongfang */ public class Facotry { private Map<String,Car> carFactory = null; { carFactory = new HashMap<>(); carFactory.put("长安",new Car("长安",120,80000)); carFactory.put("解放",new Car("解放",150,500000)); } private Facotry(){} public Car getCar(String carName){ return carFactory.get(carName); } }
xml中配置
factory-bean:指定工厂类的bean,factory-method:指定具体的工厂方法生产bean ,constructor-arg 指定工厂方法的参数
<bean id="facotry" class="com.llf.bean.factory.Facotry"></bean> <bean id="car" factory-bean="facotry" factory-method="getCar"> <constructor-arg name="carName" value="解放"></constructor-arg> </bean>
以上是关于SpringIOC容器-xml配置bean-工厂方式配置Bean的主要内容,如果未能解决你的问题,请参考以下文章