16.笔记JAVA Spring框架学习————通过FactoryBean配置Bean
• Spring 中有两种类型的 Bean, 一种是普通Bean, 另一种是工厂Bean, 即FactoryBean.
• 工厂 Bean 跟普通Bean不同, 其返回的对象不是指定类的一个实例, 其返回的是该工厂 Bean 的 getObject 方法所返回的对象
通过FactoryBean来配置Bean的示例,class指向F
创建一个类CarFactoryBean实现接口FactoryBean的全类目,property配置FactoryBean的属性。
import org.springframework.beans.factory.FactoryBean;
publicclass CarFactoryBean implements FactoryBean<Car>{
private String brand;
publicvoidsetBrand(String brand) {
this.brand = brand;
}
@Override
public Car getObject()throws Exception {
// TODO Auto-generated method stub
returnnew Car(brand,40000);
}
@Override
publicClass<?> getObjectType() {
// TODO Auto-generated method stub
return Car.class;
}
@Override
publicboolean isSingleton(){
// TODO Auto-generated method stub
returntrue;
}
}
配置app.xml内容如下
<bean id="carFactory"class="CarFactoryBean">
<property name="brand"value="bmw"></property>
</bean>
然后配置main.java如下
import java.sql.SQLException;
import javax.sql.DataSource;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.AbstractApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
import com.mchange.v2.c3p0.DataSources;
public class Main {
publicstatic void main(String[] args) throws SQLException {
//1.创建 Spring 的 IOC 容器
ClassPathXmlApplicationContextapx = new ClassPathXmlApplicationContext("app.xml");
Carcar = (Car) apx.getBean("carFactory");
System.out.println(car);
}
}
指向如下:
Car[company=bmw, brand=null, maxSpeed=0, price=40000.0]