码迷,mamicode.com
首页 > 编程语言 > 详细

Spring初学之FactoryBean配置Bean

时间:2017-04-12 22:54:28      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:schema   import   singleton   code   frame   style   boolean   ack   nts   

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

标签:schema   import   singleton   code   frame   style   boolean   ack   nts   

原文地址:http://www.cnblogs.com/hyyq/p/6701801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!