public class Car { private String name; private double price; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Car [name=" + name + ", price=" + price + "]"; } public Car(String name, double price) { super(); this.name = name; this.price = price; } }
import org.springframework.beans.factory.FactoryBean; public class CarFactoryBean implements FactoryBean<Car>{ private String brand; public void setBrand(String brand) { this.brand = brand; } //返回bean的对象 @Override public Car getObject() throws Exception { // TODO Auto-generated method stub return new Car(brand,50000); } //返回bean的类型 @Override public Class<?> getObjectType() { // TODO Auto-generated method stub return Car.class; } @Override public boolean isSingleton() { // TODO Auto-generated method stub 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的实例 但实际返回的实例却是FactoryBean的getObject()方法返回的实例 --> <bean id="car" class="com.auguigu.spring.beans.factoryBean.CarFactoryBean"> <property name="brand" value="BWM"></property> </bean> </beans>
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-factoryBean.xml"); Car car1 = (Car) ctx.getBean("car"); System.out.println(car1); Car car2 = (Car) ctx.getBean("car"); System.out.println(car1==car2); } }
输出结果:
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Car [name=BWM, price=50000.0] true