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{
	
	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格式:


 
    
    
 

 
 
 
 
 

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

你可能感兴趣的:(Spring)