Spring初学之FactoryBean配置Bean

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring初学之FactoryBean配置Bean相关的知识,希望对你有一定的参考价值。

实体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>

 

以上是关于Spring初学之FactoryBean配置Bean的主要内容,如果未能解决你的问题,请参考以下文章

spring之通过FactoryBean配置Bean

Spring中Bean的配置方式之FactoryBean

Spring之FactoryBean详解

Spring源码分析FactoryBean的使用

Spring之BeanFactory和FactoryBean接口的区别

Spring拓展接口之FactoryBean