Spring初学之FactoryBean配置Bean
本篇文章已重新总结到新博客,欢迎访问:https://ladybug.top/Spring/review-spring---spring-ioc.html
实体bean:
Car.java:
package spring.beans.factorybean; public class Car { private String name; private int price; public Car(String name, int price) { super(); this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Car [name=" + name + ", price=" + price + "]"; } }
CarFactoryBean.java:
package spring.beans.factorybean; import org.springframework.beans.factory.FactoryBean; /** * 通过factoryBean来创建实例 * @author Administrator * */ public class CarFactoryBean implements FactoryBean<Car> { private String name; private int price; public void setName(String name) { this.name = name; } public void setPrice(int price) { this.price = price; } /** * 返回一个bean实例 */ @Override public Car getObject() throws Exception { return new Car(name, price); } /** * 返回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配置文件:
<?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来创建实例 我们设置的是CarFactoryBean的属性, 返回的是Car的实例 --> <bean id="car" class="spring.beans.factorybean.CarFactoryBean"> <property name="name" value="奥迪"></property> <property name="price" value="300000"></property> </bean> </beans>