Spring使用教程(二)配置factorybean

技术分享
/**
 * 自定义的factorybean需要实现spring提供的fenctorybean接口
 * */
public class CarFactoryBean implements FactoryBean<Car>{
    //返回bean对象
    public Car getObject() throws Exception {
        // TODO Auto-generated method stub
        return new Car("BENCHI", 500000);
    }
    //返回bean类型
    public Class<?> getObjectType() {
        // TODO Auto-generated method stub
        return Car.class;
    }
    //是否单实例
    public boolean isSingleton() {
        // TODO Auto-generated method stub
        return true;
    }

}
View Code
技术分享
public class Car {
    private String brand;
    private double price;
    get...
        set...
    
}
View Code
技术分享
public class Main {
    public static void main(String[] args) {
        ApplicationContext con= new ClassPathXmlApplicationContext("car_factorybean.xml");
        Car car=(Car) con.getBean("car");
        System.out.println(car);
    }
}
View Code
技术分享
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:util="http://www.springframework.org/schema/util"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
        <!-- 实际返回的是getObject方法 -->
        <bean id="car" class="com.test.spring.factorybean1.CarFactoryBean">
            
        </bean>            
</beans>
View Code

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。