首页 > 编程语言 > 详细

spring FactoryBean配置Bean

时间:2014-06-07 13:54:22      阅读:452      评论:0      收藏:0      [点我收藏+]

概要:

bubuko.com,布布扣bubuko.com,布布扣


实例代码详解:

目录结构

bubuko.com,布布扣


Car.java

package com.coslay.beans.factorybean;

public class Car {
	private String brand;
	private double price;

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Car [brand=" + brand + ", price=" + price + "]";
	}

	public Car() {
		System.out.println("Car's Constructor...");
	}

	public Car(String brand, double price) {
		super();
		this.brand = brand;
		this.price = price;
	}

}


CarFactoryBean.java

package com.coslay.beans.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 {
		return new Car("BMW",5000000);
	}
	
	//返回bean的类型
	@Override
	public Class<?> getObjectType() {
		return Car.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
	
}


Main.java

package com.coslay.beans.factorybean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-beanfactory.xml");
		Car car = (Car) ctx.getBean("car");
		System.out.println(car);
	}
}


beans-beanfactory.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来配置Bean的实例
		class:指向FactoryBean的全类名
		property:配置FactoryBean的属性
		
		但实际返回的实例确是FactoryBean的getObject()方法返回的实例
	 -->
	<bean id="car" class="com.coslay.beans.factorybean.CarFactoryBean">
		<property name="brand" value="BMW"></property>
	</bean>

</beans>


spring FactoryBean配置Bean,布布扣,bubuko.com

spring FactoryBean配置Bean

原文:http://blog.csdn.net/coslay/article/details/28308481

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!