File: context.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="prototypeClient"
class="SpringPrototypeClient">
<property name="message1" ref="message"/>
<property name="message2" ref="message"/>
</bean>
<bean id="message" class="EmailMessage" singleton="false"/>
</beans>
File: Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] z) {
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml", Main.class);
SpringPrototypeClient client = (SpringPrototypeClient) context.getBean("prototypeClient");
client.run();
}
}
class SpringPrototypeClient {
private Message message1;
private Message message2;
public void run() {
System.out.println("Message1 " + this.message1.toString());
System.out.println("Message2 " + this.message2.toString());
System.out.println("Messages == " + (this.message1 == this.message2));
}
public void setMessage1(Message message1) {
this.message1 = message1;
}
public void setMessage2(Message message2) {
this.message2 = message2;
}
}
abstract class Message {
public Message makeCopy() {
try {
return this.getClass().newInstance();
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
}
}
}
class EmailMessage extends Message {
@Override
public String toString() {
return "EmailMessage";
}
}
Download: Spring-SpringPrototype.zip( 4,649 k)