zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【spring框架】FactoryBean

2023-09-11 14:20:52 时间

        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<Phone>{

	@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

<?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">		
	<bean id="phoneFactory" class="com.test.PhoneFactory">
	</bean>
</beans>

        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=玫瑰金]