bean的创建默认是框架利用反射机制new出来的bean实例

工厂模式:工厂帮我们创建对象,有一个专门帮我们创建对象的类,这个类就是工厂

静态工厂:工厂本身不用创建对象;通过静态方法调用,对象 = 工厂类.工厂方法名();
实例工厂:工厂本身需要创建对象;
工厂类 工厂对象 =new 工厂类();
对象=工厂对象.getPerson();

一、通过静态工厂创建bean

工厂类

package Factory;

import Test.Car;

public class StaticFactory {
public static Car getCar(String name){
Car car = new Car();
car.setCarName(name);
car.setColor("黑色");
car.setPrice(100);
return car;

}
}

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"
xmlns:p="http://www.springframework.or.g/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<!-- 静态工厂配置 -->
<!-- class指定工厂的全类名,factory-method指定需要用的静态方法,用constructor-arg来传参数 -->
<bean id="car" class="Factory.StaticFactory" factory-method="getCar">
<constructor-arg value="奔驰"></constructor-arg>
</bean>

</beans>

二、通过实例工厂创建bean

实例工厂类

package Factory;

import Test.Car;

public class Factory {
public Car getCar(String name){
Car car = new Car();
car.setCarName(name);
car.setColor("黑色");
car.setPrice(100);
return car;

}
}

xml

<!-- 实例工厂配置 -->
<!-- 先配置工厂对象,再用工厂的方法创建出对象 -->
<bean class="Factory.Factory" id="Factory"></bean>
<bean class="Test.Car" id="car02" factory-bean="Factory" factory-method="getCar">
<constructor-arg value="宝马"></constructor-arg>
</bean>

3.通过实现FactoryBean接口来写工厂类

  FactoryBean(Spring规定的一个接口)
只要是这个接口的实现类,Spring都认为是一个工厂
1.ioc容器启动的时候不会创建实例
2.FactoryBean:不论是单多实例,都是在获取的时候才会创建对象

FactoryBean实现类

package Factory;

import org.springframework.beans.factory.FactoryBean;

import Test.Car;

public class FactoryTemp implements FactoryBean<Car>{

@Override
public Car getObject() throws Exception {
// TODO Auto-generated method stub
Car car=new Car();
car.setCarName("宝马");
return car;
}

@Override
public Class<?> getObjectType() {
// TODO Auto-generated method stub
return Car.class ;
}

@Override
public boolean isSingleton() {
// TODO Auto-generated method stub
return false;
}

}

xml

<bean class="Factory.FactoryTemp" id="F">

</bean>

测试

package Test;

import static org.junit.Assert.*;

import java.applet.AppletContext;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class IOCTest2 {
private ApplicationContext ioc=new ClassPathXmlApplicationContext("IOCTest.xml");
@Test
public void test() {
Object bean = ioc.getBean("F");
System.out.println(bean);
}

}