spring框架——FactoryBean

Phone.class

public class Phone {
	private String brand;
	private String color;
	
	public String getBrand() {
		return brand;
	}
	
	public void setBrand(String brand) {
		this.brand = brand;
	}
	
	public String getColor() {
		return color;
	}
	
	public void setColor(String color) {
		this.color = color;
	}

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

PhoneFactory.java

import org.springframework.beans.factory.FactoryBean;

public class PhoneFactory implements FactoryBean{

	@Override
	public Phone getObject() throws Exception {
		Phone phone=new Phone();
		phone.setBrand("华为");
		phone.setColor("玫瑰金");
		return phone;
	}

	@Override
	public Class getObjectType() {
		return Phone.class;
	}

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

applicationContext.xml


		
	
	

Test.java

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

public class Test {

	public static void main(String[] args) {
		ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
		Phone phone=ac.getBean("phoneFactory",Phone.class);
		System.out.println(phone);
	}
}

运行结果:

Phone [brand=华为, color=玫瑰金]

 

你可能感兴趣的:(spring,spring框架,FactoryBean)