I'm observing some strange behavior with prototype-scoped class-proxied Spring beans. I'm using Spring 4.1.2.
I'm creating a single bean manually, then I invoke its method 3 times. On each method invocation a new class instance gets created - the code below prints a new ID. This means I cannot reliably store the state inside the bean.
Expected: Single instance of the class.
Observed: Each bean method invocation leads to new class instance creation.
I've dug into CGlib - it acquires the target Spring bean from the bean factory for each method invocation. The Spring bean factory happily creates a new bean each time (since it is a prototype bean).
Is this the expected behavior or a bug?
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class BeanClass1 extends SomeAbstractClass implements I1, I2 {
public void tellMe() {
System.out.println(this);
}
}
BeanClass1 bean = beanFactory.getBean(BeanClass1.class);
bean.tellMe();
bean.tellMe();
bean.tellMe();
I've switched to JDK proxies, they do not recreate beans on each bean method call.
The bean is now annotated with