您的位置:首页 > 编程语言 > Java开发

Spring_通过 FactoryBean 配置 Bean

2016-08-23 22:07 483 查看


[b]beans-factorybean.xml[/b]

<?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.hy.spring.beans.factoryBean.CarFactoryBean">
<property name="brand" value="BMW"></property>
</bean>
</beans>

[b]Car.java[/b]

package com.hy.spring.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 is Counstructor ....");
}
public Car(String brand, double price) {
super();
this.brand = brand;
this.price = price;
}
}

[b]CarFactoryBean.java[/b]

package com.hy.spring.beans.factoryBean;

import org.springframework.beans.factory.FactoryBean;

//自定义的 FactoryBean 需要spring 提供的 FactoryBean 接口
public class CarFactoryBean implements FactoryBean<Car> {

private String brand;

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

//返回Bean的对象
public Car getObject() throws Exception {
return new Car(brand,500000);
}

//返回bean的类型
public Class<?> getObjectType() {
// TODO Auto-generated method stub
return Car.class;
}

public boolean isSingleton() {
return true;
}

}

[b]Main.java[/b]

package com.hy.spring.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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: