解决单例引用原型的问题
单例引用原型有什么问题
一个人
public class User {
private String name;
private Watch wt;
}
这个人有个手表
public class Watch {
private String time;
public Watch() {
this.time = new Date().toString();
}
}
配置文件
<bean id="user" class="com.cn.mytest.lookupmethod.User">
<property name="name" value="ccc" />
<property name="wt" ref="watch" />
</bean>
<bean id="watch" class="com.cn.mytest.lookupmethod.Watch" scope="prototype">
</bean>
手表是原型模式
测试
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("lookupmethod.xml");
User user = applicationContext.getBean(User.class);
System.out.println(user);
System.out.println(user.getWt().toString());
Thread.sleep(1000l);
User user1 = applicationContext.getBean(User.class);
System.out.println(user1);
System.out.println(user1.getWt().toString());
获取2次,时间没变
问题就是,时间应该变才对
怎么解决
public abstract class User {
user换为抽象类
修改getWt方法
public abstract Watch getWt();
配置文件
<bean id="user" class="com.cn.mytest.lookupmethod.User">
<property name="name" value="ccc" />
<lookup-method name="getWt" bean="watch"></lookup-method>
</bean>
测试
com.cn.mytest.lookupmethod.User$$EnhancerBySpringCGLIB$$c179f09b@5bf0d49
Watch{time='Wed Jul 21 19:12:41 CST 2021'}
com.cn.mytest.lookupmethod.User$$EnhancerBySpringCGLIB$$c179f09b@5bf0d49
Watch{time='Wed Jul 21 19:12:42 CST 2021'}
时间变了