Bean的配置方式有三种:通过全类名(反射)、通过工厂方法(静态工厂方法&实例工厂方法)、FactoryBean.
1.首先是通过全类名来配置,这种方式最为简单也很常用,这里就不创建实例了:
在spring配置文件中配置如下:
2.通过静态工厂来配置bean实例:
首先建立静态工厂:
import java.util.HashMap;
import java.util.Map;
import com.spring.po.Car;
/**
* 静态工厂方法:直接调用某一个类的静态方法就可以返回Bean实例
*
*/
public class StaticFactory {
private static Map cars = new HashMap<>();
//初始化模拟数据
static {
cars.put("audi", new Car("audi",300000.0));
cars.put("baoma", new Car("baoma",400000.0));
}
//静态工厂方法
public static Car getCar(String name) {
return cars.get(name);
}
}
在spring配置文件中进行如下配置:
在静态工厂中,通过factory-method来获取返回的bean,通过constructor-arg标签来传递参数,获取对应的bean对象
下面是测试类:
public class FactoryTest {
public static void main(String[] args) {
//获取spring IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car1 = (Car) context.getBean("car1");
System.out.println(car1);
}
}
3.通过实例工厂方法来配置bean简单实例:
首先创建实例工厂:
import java.util.HashMap;
import java.util.Map;
import com.spring.po.Car;
/**
* 实例工厂的方法:需先创建实例工厂本身,再调用工厂的方法返回bean实例
*
*/
public class InstanceFactory {
private Map cars = null;
public InstanceFactory() { //通过构造器来初始化模拟数据
cars = new HashMap<>();
cars.put("audi", new Car("audi",300000.0));
cars.put("baoma", new Car("baoma",400000.0));
}
public Car getCar(String name) {
return cars.get(name);
}
}
在spring配置文件的配置如下:
public class FactoryTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car2 = (Car) context.getBean("car2");
System.out.println(car2);
}
}
4.通过FactoryBean来配置Bean的简单实例:
首先创建一个实现FactoryBean接口的类:
package com.spring.factoryBean;
import org.springframework.beans.factory.FactoryBean;
import com.spring.po.Car;
public class FactoryCarBean implements FactoryBean{
private String name;
public void setName(String name) {
this.name = name;
}
/**
* 返回bean
*/
@Override
public Car getObject() throws Exception {
return new Car(name, 500000.0);
}
/**
* 返回的类型
*/
@Override
public Class> getObjectType() {
return Car.class;
}
/**
* 是否单例
*/
@Override
public boolean isSingleton() {
return true;
}
}
测试类:
public class FactoryBeanTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car = (Car) context.getBean("car3");
System.out.println(car);
}
}