本文共 3437 字,大约阅读时间需要 11 分钟。
工厂方法有两种:1;静态工厂方法 2;实例工厂方法
如下一一介绍
代码示例:
Car_StaticFactory.java
package com.atguigu.spring.bean;import java.util.HashMap;import java.util.Map;/** * .静态工厂方法:直接调用某一个类的静态方法就可以返回bean的实例 */public class Car_StaticFactory { private static Mapcars =new HashMap (); static { cars.put("benchi", new Car("benchi",80000)); cars.put("baoma", new Car("baoma",80000)); } //静态工厂方法 public static Car getCar(String name) { return cars.get(name); }}
Car.java
package com.atguigu.spring.bean;public class Car { private String brand; private double price; public void setBrand(String brand) { this.brand = brand; } public void setPrice(Double price) { this.price = price; } public Car(String brand, double price) { super(); this.brand = brand; this.price = price; System.out.println("调用构造函数"); } @Override public String toString() { return "Car [brand=" + brand + ", price=" + price + "]"; } }
application.xml
Main.java
package com.atguigu.spring.bean;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main { public static void main(String[] args) { ConfigurableApplicationContext configurableApplicationContext=new ClassPathXmlApplicationContext("application.xml"); Car car1=(Car) configurableApplicationContext.getBean("car1"); System.out.println(car1); configurableApplicationContext.close(); }}
—在 bean 的 factory-bean 属性里指定拥有该工厂方法的 Bean
—在 factory-method 属性里指定该工厂方法的名称
—使用 construtor-arg 元素为工厂方法传递方法参数
代码演示
Car_Instance
package com.atguigu.spring.bean;import java.util.HashMap;import java.util.Map;/** * .实例工厂方法,即需要创建工厂本身,在调用工厂的实例方法返回bean的实例 */public class Car_Instance { private static Mapcars =new HashMap (); public Car_Instance() { cars.put("benchi", new Car("benchi", 8000000)); cars.put("baoma", new Car("baoam", 4000000)); } public Car getCar(String brand) { return cars.get(brand); } }
Car.java
package com.atguigu.spring.bean;public class Car { private String brand; private double price; public void setBrand(String brand) { this.brand = brand; } public void setPrice(Double price) { this.price = price; } public Car(String brand, double price) { super(); this.brand = brand; this.price = price; System.out.println("调用构造函数"); } @Override public String toString() { return "Car [brand=" + brand + ", price=" + price + "]"; } }
application.xml
Main.java
package com.atguigu.spring.bean;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main { public static void main(String[] args) { ConfigurableApplicationContext configurableApplicationContext=new ClassPathXmlApplicationContext("application.xml"); Car car2=(Car) configurableApplicationContext.getBean("car2"); System.out.println(car2); configurableApplicationContext.close(); }}
转载地址:http://mrozi.baihongyu.com/