Spring入门第十三课

Posted alittlecomputer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring入门第十三课相关的知识,希望对你有一定的参考价值。

通过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[email protected]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入门第十三课的主要内容,如果未能解决你的问题,请参考以下文章

Spring入门第三课

Kotlin入门第三课:数据类型

StoneDB Class入门第三课:StoneDB的编译安装

StoneDB Class入门第三课:StoneDB的编译安装

JavaScript入门第十三章(函数)

Python 入门第十三天