【尚硅谷】spring学习笔记(11):FactoryBean
程序员文章站
2022-05-23 18:13:36
...
实现 FactoryBean 接口在 Spring IOC 容器中配置 Bean
- Spring 中有两种类型的 Bean, 一种是普通Bean, 另一种是工厂Bean, 即FactoryBean.
- 工厂 Bean 跟普通Bean不同, 其返回的对象不是指定类的一个实例, 其返回的是该工厂 Bean 的 getObject 方法所返回的对象
package com.atguigu.spring.beans.factorybean;
public class Car {
private String brand;
private double price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
public Car(String brand, double price) {
super();
this.brand = brand;
this.price = price;
}
public Car() {
System.out.println("car的构造器");
}
}
package com.atguigu.spring.beans.factorybean;
import org.springframework.beans.factory.FactoryBean;
//自定义的FactoryBean需要实现FactoryBean接口
public class CarFactoryBean implements FactoryBean<Car> {
private String brand;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
//还回bean对象
@Override
public Car getObject() throws Exception {
return new Car(brand,600000);
}
//还回bean的类型
@Override
public Class<?> getObjectType() {
return Car.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
<?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">
<!--
通过FactoryBean来配置Bean的实例
class:指向FactoryBean的全类名
property:配置FactoryBean的属性
但实际还回的实例确实FactoryBean的getObject()方法还回的实例
-->
<bean id="car" class="com.atguigu.spring.beans.factorybean.CarFactoryBean">
<property name="brand" value="宝马"></property>
</bean>
</beans>
package com.atguigu.spring.beans.factorybean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext apl = new ClassPathXmlApplicationContext("beans-beanfactory.xml");
Car car = (Car) apl.getBean("car");
System.out.println(car);
}
}
结果:
六月 13, 2018 2:18:44 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org[email protected]6193b845: startup date [Wed Jun 13 14:18:44 CST 2018]; root of context hierarchy
六月 13, 2018 2:18:44 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-beanfactory.xml]
Car [brand=宝马, price=600000.0]