在实例化bean时,除了setter,constructor方法外,还有实例工厂方法,和静态工厂方法。
看代码:
People类的代码如下:
package com.timo.domain; public class People { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
//工厂方法如下:
package com.timo.domain; public class PeopleFactory { private static People people=new People(); //this is non-static method. public People createPeopleInstance(){ return people; } }
配置文件
applicationContext-instance-factory.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"> <import resource="applicationContext.xml"/> <import resource="applicationContext2.xml"/> <bean id="peopleFactory" class="com.timo.domain.PeopleFactory"></bean> <bean id="people" factory-bean="peopleFactory" factory-method="createPeopleInstance"> <property name="name" value="曹操"/> <property name="age" value="56"/> </bean> <!-- more bean definitions go here --> </beans>
测试类如下:
package com.timo.test; import com.timo.domain.People; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test5 { public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-instance-factory.xml"); People people = applicationContext.getBean(People.class); System.out.println("name="+people.getName()+" age="+people.getAge()); } }