Spring FactoryBean

Spring  FactoryBean 是创建 复杂的bean,一般的bean 直接用xml配置即可,如果一个bean的创建过程中涉及到很多其他的bean 和复杂的逻辑,用xml配置比较困难,这时可以考虑用FactoryBean

例子如下:

1:创建一个Car类(是为了简便)一般不能直接给出Car类,如果是这样直接注入就可以或者Car对象了,这里只是为了简便。

package com.myapp.core.factorybean;

public class Car {
  private  String  make;
  private  int year;
	public String getMake() {
		return make;
	}
	public void setMake(String make) {
		this.make = make;
	}
	public int getYear() {
		return year;
	}
	public void setYear(int year) {
		this.year = year;
	}
	  
}

2:一个FactoryBean的实现拥有创建car

package com.myapp.core.factorybean;

import org.springframework.beans.factory.FactoryBean;

public class MyCarFactoryBean  implements FactoryBean<Car>{
	
	private String  make;
	
	private  int  year;

	public void setMake(String make) {
		this.make = make;
	}

	public void setYear(int year) {
		this.year = year;
	}

	@Override
	public Car getObject() throws Exception {
		// TODO Auto-generated method stub
		
		//Here  is a complex  car  object  created
		 // wouldn't be a very useful FactoryBean
	    // if we could simply instantiate the object!
		Car  car  = new  Car();
		
		if(year != 0){
		   car.setYear(this.year);
		}
		
		if("make".equals(make)){
			car.setMake("we are making  bla bla  bla");
		}else{
			car.setMake(this.make);
		}
		
		return  car;
	}

	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return Car.class;
	}

	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}

}

以上中创建car太简单了,如果太简单就没有必要用FactoryBean创建了,可以写的复杂些。


3:Person 引用一个car


package com.myapp.core.factorybean;

public class Person {
 
	private  Car  car;

	public Car getCar() {
		return car;
	}

	public void setCar(Car car) {
		this.car = car;
	}
	
	public  String  toString(){
		
		return  car.getMake()+"::::"+car.getYear();
	}
}

4:配置引用xml格式:


 <bean id="car" class="com.myapp.core.factorybean.MyCarFactoryBean">
    <property name="make" value="makeing car"/>
    <property name="year"  value="123"/>
 </bean>

 <bean id="person" class="com.myapp.core.factorybean.Person">
 
 <property name="car" ref="car"/>
 
 </bean>

5:编写测试类测试:

package com.myapp.core.factorybean;

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

public class MainTest {
  public static void main(String[] args) {
	
	  ApplicationContext  context  = new  ClassPathXmlApplicationContext("resource/others.xml");
	  
 Person  person =   (Person)context.getBean("person");
	  
	 // Car  car =   (Car)context.getBean("car");
	  
	//  System.out.println(car);
	System.out.println(person);
}
}

测试结果 makeing car::::123
利用FactoryBean创建car成功
只是为了说明思想。因为这个接口太重要了。在Spring中有很多类实现了改接口over
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值