码迷,mamicode.com
首页 > 编程语言 > 详细

SpringIOC容器-xml配置bean-工厂方式配置Bean

时间:2020-04-18 18:41:01      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:code   ack   new   auth   factor   style   xml配置   actor   静态方法   

一、实验使用实体类

技术图片

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

标签:code   ack   new   auth   factor   style   xml配置   actor   静态方法   

原文地址:https://www.cnblogs.com/linglongfang/p/12727259.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!