Car.java
package com.gong.spring.beans.factory;public class Car { private String name; private double price; public String getname() { return name; } voID setname(String name) { this.name = getPrice() { price; } voID setPrice( price) { this.price =public Car(String name,super(); name; price; } @OverrIDe String toString() { return "Car [name=" + name + ",price=" + price + "]"; } }
InstanceFactory.java
import java.util.HashMap; java.util.Map;//实例工厂方法,先要创建工厂方法本身,再调用工厂的实例方法返回Bean的实例 InstanceFactory { private Map<String,Car> cars = null; InstanceFactory() { cars = new HashMap<String,Car>(); cars.put("baoma",1)">new Car("baoma",200000)); cars.put("benchi",1)">new Car("benchi",300000)); } Car getCar(String name) { 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 ID="carFactory" class="com.gong.spring.beans.factory.InstanceFactory"></bean> 通过实例工厂方法配置Bean ="car" factory-bean factory-method="getCar"> constructor-arg value="baoma"constructor-arg</>beans>
Main.java
org.springframework.context.support.ClasspathXmlApplicationContext; Main { static 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全部内容,希望文章能够帮你解决spring之通过实例工厂方法配置Bean所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)