笔记内容及代码来源于尚硅谷的免费在线课
地址:http://www.gulixueyuan.com/my/course/46
FactoryBean.class有3个方法
getObject() 返回bean本身
getObjectType() 返回bean的实例
isSingleton 返回bean是否为单例
有时在配置一个bean的时候会用到IOC容器的其他bean,这个是有用factorybean配置是最合适的
Car.java,和Factory的Car类没有区别
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; } public Car(String brand, double price) { this.brand = brand; this.price = price; } public Car() { System.out.println("Car‘s Constructor..."); } @Override public String toString() { return "Car{" + "brand=‘" + brand + ‘\‘‘ + ", price=" + price + ‘}‘; } }
CarFactoryBean.java 自定义的FactoryBean需要实现FactoryBean接口
package com.atguigu.spring.beans.factorybean; import org.springframework.beans.factory.FactoryBean; //自定义的FactoryBean需要实现FactoryBean接口 public class CarFactoryBean implements FactoryBean<Car> { private String brand; public void setBrand(String brand) { this.brand = brand; } //返回bean的对象 public Car getObject() throws Exception { return new Car(brand,500000); } /** * 返回bean的类型 */ public Class<?> getObjectType() { return Car.class; } public boolean isSingleton() { return true; } }
beans-beanfactory.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 通过FactoryBean来配置Bean的实例 class:指向FactoryBean的全类名 property:配置FactoryBean的属性 但实际返回的实例确实FactorBean的getObject()方法返回的实例! --> <bean id="car" class="com.atguigu.spring.beans.factorybean.CarFactoryBean"> <property name="brand" value="BMW"></property> </bean> </beans>
main.java
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 ctx = new ClassPathXmlApplicationContext("beans-beanfactory.xml"); Car car = (Car) ctx.getBean("car"); System.out.println(car); } }
原文:https://www.cnblogs.com/Anan2020/p/13030446.html