FactoryBean的使用详解...

来源:互联网 发布:浙江堂鼓网络 编辑:程序博客网 时间:2024/04/29 04:49
<strong><span style="font-size:14px;">package com.spring.factory2;public class Car2 {private int brand;private double price;public Car2(int brand,double price){this.price = price;this.brand = brand;}public int getBrand() {return brand;}public void setBrand(int brand) {this.brand = brand;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}@Overridepublic String toString() {return "Car [brand=" + brand + ", price=" + price + "]";}}</span></strong>
package com.spring.factory2;import org.springframework.beans.factory.FactoryBean;public class CarFactoryBean implements FactoryBean<Car2>{private int brand;public void setBrand(int brand) {this.brand = brand;}public Car2 getObject() throws Exception {return new Car2(brand,8999);}public Class<?> getObjectType() {return Car2.class;}public boolean isSingleton() {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"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"><bean id="car2" class="com.spring.factory2.CarFactoryBean"><property name="brand" value="1000000000"></property></bean></beans>

package com.spring.factory2;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) {ApplicationContext appContext = new ClassPathXmlApplicationContext("beans-factory2.xml");Car2 car = (Car2)appContext.getBean("car2");System.out.println(car);}}



0 0
原创粉丝点击