Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bean marked with prototype scope not working in Spring

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 ");      
    }

}
like image 535
Anand Avatar asked Dec 10 '12 14:12

Anand


2 Answers

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

like image 182
Biju Kunjummen Avatar answered Oct 25 '22 20:10

Biju Kunjummen


I think you have to make a new Child yourself each time or indeed use the spring context to get a fresh bean.

Spring will only create a new instance when it needs to inject something (in case of prototype). When you are in a class you are effectively out of the scope of spring.

Here is a similar post: @Scope("prototype") bean scope not creating new bean

http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-prototype Parts 4.4.2 and 4.4.3 are relevant.

like image 20
tom Avatar answered Oct 25 '22 19:10

tom