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

Spring入门第十三课

时间:2017-05-21 20:37:36      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:public   todo   ssi   log   override   return   port   1.0   ext   

通过FactoryBean来配置Bean

package logan.spring.study.factoryBean;

public class Car {
    
    private String brand;
    private int price;
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Car [brand=" + brand + ", price=" + price + "]";
    }
    public Car(String brand, int price) {
        super();
        this.brand = brand;
        this.price = price;
    }
}
package logan.spring.study.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的对象
    @Override
    public Car getObject() throws Exception {
        // TODO Auto-generated method stub
        return new Car(brand,500000);
    }

    //返回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的实例 
    class:指向FactoryBean的全类名
    property:配置FactoryBean的属性
    但实际上返回的实例却是FactoryBean的getObject()方法返回的实例
    -->
    <bean id="car" class="logan.spring.study.factoryBean.CarFactoryBean">
        <property name="brand" value="BMW"></property>
    </bean>

</beans>

下面是输出结果:

五月 21, 2017 7:44:58 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7aec35a: startup date [Sun May 21 19:44:58 CST 2017]; root of context hierarchy
五月 21, 2017 7:44:58 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-beanfactory.xml]
Car [brand=BMW, price=500000]

 

Spring入门第十三课

标签:public   todo   ssi   log   override   return   port   1.0   ext   

原文地址:http://www.cnblogs.com/LoganChen/p/6885756.html

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