通过工厂方法配置bean

通过指向静态工厂的全类名,及factory-method,传入参数获取bean。

 

配置为:

    <bean id="schoolBean" class="com.pfSoft.beanFactory.myFactory" factory-method="getSchool">
        <constructor-arg value="wuda"></constructor-arg>
    </bean>

 

新增静态工厂类:

public class myFactory {
	
	private static Map<String, School> schools=new HashMap<String, School>();
	
	static{
		schools.put("wuda", new School("武大", "武汉东湖之滨"));
		schools.put("qinghua", new School("清华", "海淀黄庄"));
	}
	
	public static School getSchool(String schoolName) {
		return schools.get(schoolName);
	}
}

新增 bean:school

public class School {
	private String schoolName;
	private String address;
	/**
	 * 
	 * @return the schoolName
	 */
	public String getSchoolName() {
		return schoolName;
	}
	/**
	 * @param schoolName the schoolName to set
	 */
	public void setSchoolName(String schoolName) {
		this.schoolName = schoolName;
	}
	/**
	 * 
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}
	/**
	 * @param address the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}
	
	public School(String schoolName, String address) {
		super();
		this.schoolName = schoolName;
		this.address = address;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "School [schoolName=" + schoolName + ", address=" + address
				+ "]";
	}
}

 测试代码:

private ApplicationContext ctx;
	
	@Before
	public void init() {
		ctx=new  ClassPathXmlApplicationContext("spring-beanFactory.xml");
	}
	
	@Test
	public void testBeanStaticFactory() {
		School school= (School) ctx.getBean("schoolBean");
		System.out.println(school.toString());
	}

 输出为:School [schoolName=武大, address=武汉东湖之滨]

实例工厂方法

有别与静态工厂方法,想要调用需要先创建工厂本身的实例来返回bean的实例。

在本例中需要先配置工厂的实例。

配置如下:

    <bean id="instanceFactoryBean" class="com.pfSoft.beanFactory.InstanceFactory"></bean>
    <bean id="schoolBean2" factory-bean="instanceFactoryBean" factory-method="getSchool">
        <constructor-arg value="qinghua"></constructor-arg>
    </bean>

 

实例工厂代码如下:

public class InstanceFactory {
    
    private   Map<String, School> schools=new HashMap<String, School>();
    
    public InstanceFactory() {
        schools.put("wuda", new School("武大", "武汉东湖之滨"));
        schools.put("qinghua", new School("清华", "海淀黄庄"));
    }
    
    public School getSchool(String schoolName) {
        return schools.get(schoolName);
    }
}

 

测试代码如下:

    @Test
    public void testBeanStaticFactory() {
        School school= (School) ctx.getBean("schoolBean");
        School school2= (School) ctx.getBean("schoolBean2");
        System.out.println(school.toString());
        System.out.println(school2.toString());
    }

 

 输出结果为:

School [schoolName=武大, address=武汉东湖之滨]
School [schoolName=清华, address=海淀黄庄]

 

可以看到school2是通过实例工厂创建出来的。

posted on 2016-04-27 23:23  falcon_fei  阅读(206)  评论(0编辑  收藏  举报