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

spring之通过静态工厂方法配置Bean

时间:2020-01-06 14:34:52      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:--   info   price   utf-8   ring   port   通过   his   tostring   

Car.java

package com.gong.spring.beans.factory;

public class Car {
    private String name;
    private double price;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public Car(String name, double price) {
        super();
        this.name = name;
        this.price = price;
    }
    @Override
    public String toString() {
        return "Car [name=" + name + ", price=" + price + "]";
    }
    
}

StaticFactory.java

package com.gong.spring.beans.factory;

import java.util.HashMap;
import java.util.Map;

//静态工厂方法:直接调用一个类的静态工厂方法就可以返回Bean的实例
public class StaticFactory {
    public static Map<String,Car> cars = new HashMap<String,Car>();
    static {
        cars.put("baoma",new Car("baoma",200000));
        cars.put("benchi",new Car("benchi",300000));
    }
    public static Car getCar(String name) {
        return cars.get(name);
    }
}

beans-factory.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,不是配置静态工厂方法实例,而是配置Bean实例 -->
    <!-- class:指向静态工厂方法的全类名
         factory-method:指向静态工厂方法的名字
         constructor-arg:如果静态工厂方法需要传入参数,使用这个来配置参数 -->
    <bean id="car" class="com.gong.spring.beans.factory.StaticFactory" factory-method="getCar">
        <constructor-arg value="baoma"></constructor-arg>
    </bean>
</beans>

Main.java

package com.gong.spring.beans.factory;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        //1.创建spring的IOC容器对象
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml");
        //2.从容器中获取Bean实例
        Car car = (Car) ctx.getBean("car");
        System.out.println(car.toString());
        ctx.close();
    }
}

输出:

技术图片

spring之通过静态工厂方法配置Bean

标签:--   info   price   utf-8   ring   port   通过   his   tostring   

原文地址:https://www.cnblogs.com/xiximayou/p/12155856.html

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