Bean marked with prototype scope not working in Spring

java, prototype-scope, scope, spring

Solution

The fix is simply to mark the prototype bean as a scoped proxy, what this means is that a when you inject a bean of a smaller scope into a larger scope(like in your case where a prototype is injected into a singleton) then a proxy of the bean will be injected into the larger scope and when methods of the bean are invoked via proxy, the proxy understands the scope and will respond appropriately.

@Component
@Scope(value=BeanDefinition.SCOPE_PROTOTYPE, proxyMode=ScopedProxyMode.TARGET_CLASS)
public class Child{

Here is a reference

Another option could be to use something called lookup method injection described here

Problem

I have two beans, Parent and Child. Child bean I have declared as of Protoype scope. I want new child object is used to call any child's method in the Parent class. For eg. in the below example,I want statement 1 calls method sayHi on different child object and statement 2 calls sayHi1 on different child object. One way is to implement ApplicationContextAware and get new child object using `context.getBean("")` before calling any child's method. But i don't want to do that. Is there any other alternative? ``` @Component public class Parent{ @Autowired Child child; public void sayHello(){ child.sayHi(); -------------- (1) } public void sayHello1(){ child.sayHi1(); --------------- (2) } } @Component @Scope(value=BeanDefinition.SCOPE_PROTOTYPE) public class Child{ public void sayHi(){ System.out.println("Hi Spring 3.0"); } public void sayHi1(){ System.out.println("Hi1 Spring 3.0 "); } } ```

Original source

Related problems