CurrentTime.java
import java.util.Calendar;
public class CurrentTime {
private Calendar now=Calendar.getInstance();
public void printCurrentTime() {
System.out.println(now.getTime());
}
}
lookup.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-4.0.xsd">
<bean id="currentTime" class="cn.hxex.springcore.lookup.CurrentTime" scope="prototype"></bean>
<bean id="lookupBean" class="cn.hxex.springcore.lookup.LookupBean" scope="singleton">
<lookup-method name="createCurrentTime" bean="currentTime"></lookup-method>
<property name="currentTime" ref="currentTime"></property>
</bean>
</beans>
LookupMain.java
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class LookupMain {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ClassPathResource resource=new ClassPathResource("cn/hxex/springcore/lookup/LookupBeans.xml");
XmlBeanFactory factory=new XmlBeanFactory(resource);
// LookupBean lookupBean=(LookupBean) factory.getBean("lookupBean");
// System.out.println("get");
// lookupBean.getCurrentTime().printCurrentTime();
// System.out.println("create");
// lookupBean.createCurrentTime().printCurrentTime();
// System.out.println("------------");
// Thread.sleep(1000);
// System.out.println("get");
// lookupBean.getCurrentTime().printCurrentTime();
// System.out.println("create");
// lookupBean.createCurrentTime().printCurrentTime();
// System.out.println("-----------");
CurrentTime ct=(CurrentTime) factory.getBean("currentTime");
System.out.println("一");
ct.printCurrentTime();
System.out.println("-----------");
Thread.sleep(5000);
System.out.println("二");
ct.printCurrentTime();
}
}
你这个测试方法并不能说明问题的呀,你打印了两次 ct ,同一个对象的时间属性当然是一样的啦。
应该是间隔一段时间先后获取两次 Bean ID 相同的实例,再打印时间,肯定是不同的。这样测试试一下:
CurrentTime ct1=(CurrentTime) factory.getBean("currentTime");
System.out.println("一");
ct1.printCurrentTime();
Thread.sleep(5000);
CurrentTime ct2=(CurrentTime) factory.getBean("currentTime");
System.out.println("一");
ct2.printCurrentTime();
prototype 方式,第二次获取时会创建一个新实例,时间也是不同的。