1. 程式人生 > >Spring入門第十三課

Spring入門第十三課

utf cto ext imp 輸出 app 類型 sta loading

通過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.ClassPathXmlApplicationContex[email protected]: 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入門第十三課